Variations on SQL queries

  • Thread starter Deleted member 43669
  • Start date
Status
Not open for further replies.
D

Deleted member 43669

Guest
As an SQL fan, I have lots of SQL statements in my application (right now most are embedded quoted within Java code, but I hope to change that). Of course, we all know the parameterization stuff:

Code:
execute("select * from foo where bar = :bar and baz >= :baz", { "bar": myVar, "baz" : 4 });

However, there's the typical situation when you want to execute variations on SQL queries which are not really well covered by parameterization. For instance, a typical query to display a sortable table; which you might want to execute with different ORDER BY clauses, or a search functionality which lets you choose and combine different search criteria.

You can of course use string concatenation to build those queries, and typically it's not difficult to do it "properly", but I'm wondering if anyone's using a more "sophisticated" approach.

I was thinking SQL-like DSL languages, i.e. Query.build().select(ALL).from("foo").toSQL(), where you can programatically build SQL- this approach would work pretty well in these situations, but I've not found yet a suitable library to do this...

edit: there's also stored procedures... but I'm unsure about that...

... any other ideas?

Alex
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
I know Java doesn't have LINQ, but surely Hibernate/Spring/etc don't all suck?

a search functionality which lets you choose and combine different search criteria.
That's not too hard to do in pure SQL. One way...

Code:
CREATE PROC QuasiDynamicSearch
    @param1       INT = NULL,
    @param2       INT = NULL,    
    @param3       INT = NULL,    
    ...
AS

SELECT * FROM table t1
INNER JOIN table2 t2 ON ...
LEFT JOIN table3 ON ...
WHERE t1.criterion1 = COALESCE(@param1, t1.criterion1)
WHERE t2.criterion2 = COALESCE(@param2, t2.criterion2)
WHERE COALESCE(t3.criterion3, -1) = COALESCE(@param2, t3.criterion3, -1)
WHERE ...
(omg, an area I actually prefer Sybase syntax :eek: -- MSSQL calls it "isnull" instead of "coalesce" -- lame)

Hopefully your DB supports table-valued variables and parameters. If like me you're stuck with 90s technology, you can use one of these methods to pass in sets. If the sets aren't already in a format like XML or CSV on the client, I prefer this method. Moderate overhead the first time you make a parameter table, but easy going thereafter. In the proc above, you'd build up a temp table for each set-valued parameter, adding extra logic when necessary...
Code:
SELECT INTO #param3 FROM (
    SELECT foo FROM Param3_xfer WHERE Key = @param3
    UNION
    SELECT -1
)
...then adjust predicates in the main query accordingly...
Code:
WHERE COALESCE(t3.criterion3, -1) IN #param3

Note: for any random input, dynamic SQL is more likely to pick the "right" index. I just happen to hate DSQL. Workaround: write helper sprocs/funcs optimized that nail the most important 2-3 query plans, then in place of the giant SELECT, do something like IF(...) EXEC proc1 ELSE IF(...) EXEC proc2 ....
 

Timbukto

Ars Scholae Palatinae
806
MS SQL has COALESCE as well. COALESCE is what you'll want to use unless you want to deal with NVL, ISNULL, and IFNULL(not to be confused with NULLIF) for the respective dbs. There are some datatype and performance considerations.

I think variations of SQL of this sort (i.e. differing search criteria/order by's, etc) are pretty well explained through google-fu(mssql ref http://www.sommarskog.se/dyn-search-2005.html) and there are different solutions depending on the situation as already covered in this thread.

Lets talk about a possibly? worst case scenario...user defined/ad hoc pivots. Lets make the assumption that pivoting of data is advantageous to be done on the SQL engine and not client side. And the assumption that very few (do any?) ORMS have much support for PIVOT statements much less ad hoc ones. And the assumption that whatever PIVOT functions built into the db only support hardcoded field values with static sql.

I just did it quick and dirty and used dynamic SQL for user-defined/ad hoc pivots.

Unsure at this point if my co-worker's eyes wouldn't have glazed over much the same were it built with expression trees and/or something like NLinq.
 
D

Deleted member 43669

Guest
Richard Berg":3ud2bx9c said:
I know Java doesn't have LINQ, but surely Hibernate/Spring/etc don't all suck?

Hibernate is an ORM- if I understand correctly, LINQ is not an ORM. I like LINQ because it maps fairly well to SQL, whereas Hibernate does not. Hibernate does provide Criteria queries, which kind of let me do what I want, but I'd rather use something more SQLy.

There's Squill, Quaere, Jequel, Jaqu... take your pick, but none seem mature enough.

Yes, if there was a thingy that connected to a database, parsed all metadata and gave me a set of classes to perform queries programatically, I'd be all over that. I'd write my own, but it would end up more half-assed than what's out there.

So it seems that my other "clean" option is stored procedures... which also accomplishes what I want, but does not please me either.

Drats.
 

Timbukto

Ars Scholae Palatinae
806
http://www.simpleorm.org/sorm/whitepaper.html

How does this one look? Far more lightweight than Hibernate, but I have no real experience with either.

Also I like using stored procedures and understand what you are intending to say but I think its more accurate to break-down the pure-SQL solutions as the static sql based solution as shown above using parameters with ISNULL or Coalesce type statements, or full-blown dynamic sql with control flow statements, etc. Saying just 'stored procedures' is a bit vague and may mis-characterize them as a tool you should only use as a last resort regardless of context (although it may be true depending on the situation that the pure-sql solutions here may not be ideal for your given intent).
 

Richard Berg

Ars Legatus Legionis
43,037
Subscriptor
Hibernate is an ORM- if I understand correctly, LINQ is not an ORM. I like LINQ because it maps fairly well to SQL, whereas Hibernate does not. Hibernate does provide Criteria queries, which kind of let me do what I want, but I'd rather use something more SQLy.
LINQ is a language feature which [among other things] allows .NET ORMs to meld seamlessly into idiomatic C# code. Any .NET ORM that doesn't leverage LINQ is putting itself at a major disadvantage -- which is why so many people latched onto LINQ2SQL, despite its lack of maturity or featureset relative to NHibernate.

While Java doesn't have LINQ, you'd hope that Java-based ORMs would at least attempt a similar level of language integration where possible.
 

warrens

Ars Legatus Legionis
11,415
koala":25ka6sed said:
Well, actually I don't want an ORM. If I did, Hibernate's Criteria would probably be fine. I want something similar to LINQ2SQL, I guess, or the fully-SQL solutions presented above.

If you go with NHibernate, you could use the recently-released NHibernate-Linq library to do LINQ operations against NHibernate.
 

Timbukto

Ars Scholae Palatinae
806
koala":2vkytva6 said:
Well, actually I don't want an ORM. If I did, Hibernate's Criteria would probably be fine. I want something similar to LINQ2SQL, I guess, or the fully-SQL solutions presented above.

Not an ORM expert myself, but doesn't an ORM give you a superset of what you want? Mainly language integrated queries, object mapping, and persistence. I would believe it should be fairly trivial to side-step or avoid the latter 2 and be able to use the 1st. Thus a lightweight ORM that gives you close to SQL abilities (to drop down into SQL when you need to) should be close to what you want? I'm not an ORM advocate either, but after working with both the static SQL or dynamic SQL routes, the language integrated queries do make a lot of sense to me for various reasons (static sql solution has performance and maintenance implications, dynamic sql solution is more performant but has major maintenance implications, ORM language integrated queries will still be performant depending on the ORM but may be easier on your co-workers eye's or your own down the road).
 
koala":mbfp07vk said:
As an SQL fan, I have lots of SQL statements in my application (right now most are embedded quoted within Java code, but I hope to change that).
Please don't do this, putting SQL in the application. Use functions & stored procedures (if using Oracle, within Packages).

Function & Stored Procedure use means parameterized queries, which are less prone to SQL injection. It also means less data is sent over the wire, improving speed. When possible/necessary, stored procedures can encapsulate operations - the operation is contained within the database, there's no back & forth between the DB and the application which improves speed and operations can be atomic...

koala":mbfp07vk said:
However, there's the typical situation when you want to execute variations on SQL queries which are not really well covered by parameterization. For instance, a typical query to display a sortable table; which you might want to execute with different ORDER BY clauses, or a search functionality which lets you choose and combine different search criteria.

SQL supports if logic (IE: CASE is ANSI, but DECODE/IF/etc) in the ORDER BY, not it's not very flexible. Most of the time, this requires using dynamic SQL.

FYI: SQL Server 2000+ supports COALESCE.
 

SNK111

Seniorius Lurkius
2
Check this link: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html ) for details on how to connect to SQL Server database from Java database applications as well as C#.NET database applications. It also describes how to pass embedded SQL queries, calling stored procedures, pass parameter etc.

http://www.shahriarnk.com/
 
Status
Not open for further replies.