iTranslated by AI
Why Not Just Use SQL Instead of a DSL?
ORMs are good at CUD operations, but they struggle with R (SELECT) operations.
While the goal of a DSL is to translate into SQL, you have to go out of your way to "reverse-translate" (into the DSL) even when you already know the answer (SQL).
On top of that, the syntax of DSLs varies between different ORM libraries, making it a world even more filled with dialects than SQL itself.
So I'd like to ask again: Why don't you use SQL?
Reasons for Avoiding SQL
I can imagine five major reasons:
- Fear of SQL injection
- Low versatility
- Static analysis and compilation checks don't work
- Mapping to entity models is tedious
- Poor maintainability of long queries
Are these still really problems today?
Wouldn't it be solved if we could analyze and manipulate SQL?
Q: I'm afraid of SQL injection
Depending on the team's skill level, it can be a bit scary.
Concatenating SQL strings is dangerous.
A: No need to worry if you can synthesize SQL and search conditions
Analyzing and manipulating SQL can solve this.
First, represent the search conditions as a model.
const state = {
price: { min: 10, max: 100 },
article_name: { like: '%super%' }
};
Next, prepare the SQL.
-- baseQuery
SELECT
a.article_id
, a.article_name
, a.price
FROM
article AS a
If you could synthesize these and create a parameter query without writing any WHERE conditions at all...
SELECT
a.article_id
, a.article_name
, a.price
FROM
article AS a
WHERE
a.price >= $1
AND a.price <= $2
AND a.article_name like $3
SQL might not be so bad after all.
Q: Low versatility
SQL statements are hard-coded.
For complex search conditions, string concatenation is unavoidable.
A: No need to worry if you can synthesize SQL and search conditions at a high level
Analyzing SQL down to CTEs and subqueries and being able to manipulate search conditions against physical tables solves this.
First, prepare the search conditions.
const state = { user_id: 42, name: 'Alice' };
Next, prepare a complex SQL query.
WITH
cte_users AS (
SELECT
id
, name
FROM
users
WHERE
active = true
)
SELECT
*
FROM
(
SELECT
id AS user_id
, name AS user_name
FROM
cte_users
) AS sub
If we could synthesize these and insert search conditions at a position close to the physical data source...
WITH
cte_users AS (
SELECT
id
, name
FROM
users
WHERE
active = true
AND name = $1
)
SELECT
*
FROM
(
SELECT
id AS user_id
, name AS user_name
FROM
cte_users
WHERE
id = $2
) AS sub
SQL might not be so bad after all.
Q: Static analysis and compilation checks don't work
How can we detect inconsistencies on the query side when the schema changes?
How do we know if existing SQL has broken without noticing (regression)?
A: No need to worry if you can statically inspect SQL
By analyzing the schema used in the SQL, you can perform schema compliance checks.
First, prepare the schema information.
const tableSchemas = [
{ name: 'users', columns: ['id', 'name'] }
];
Next, prepare the SQL.
SELECT id, age FROM users
If you could synthesize these and detect errors...
Table 'users' contains undefined columns: age.
SQL might not be so bad after all.
Mapping to entity models is tedious
Mapping is a pain.
A: No need to worry if you eliminate the need for mapping itself
This can be solved by transforming SQL into a query that returns JSON.
First, prepare the SQL.
SELECT
sale_id
, sale_date
, sale_total
, detail_id
, detail_quantity
, detail_price
, product_id
, product_name
, product_category
FROM
sale_full_report
Next, create the mapping definition.
const mapping: JsonMapping = {
rootName: "Sales",
rootEntity: {
id: "sale",
name: "Sale",
columns: {
"id": "sale_id",
"date": "sale_date",
"total": "sale_total"
}
},
nestedEntities: [
{
id: "saleDetails",
name: "SaleDetails",
parentId: "sale",
propertyName: "details",
relationshipType: "array", // Sale has multiple SaleDetails (downstream)
columns: {
"id": "detail_id",
"quantity": "detail_quantity",
"price": "detail_price"
}
},
{
id: "product",
name: "Product",
parentId: "saleDetails",
propertyName: "product",
relationshipType: "object", // Each SaleDetail has one Product (upstream)
columns: {
"id": "product_id",
"name": "product_name",
"category": "product_category"
}
}
],
useJsonb: true
};
If you could synthesize these and create a scalar query that returns JSON...
with "origin_query" as (select "sale_id" , "sale_date" , "sale_total" , "detail_id" , "detail_quantity" , "detail_price" , "product_id" , "product_name" , "product_category" from "sale_full_report") , "cte_object_depth_1" as (select * , case when "product_id" is null and "product_name" is null and "product_category" is null then null else jsonb_build_object('id', "product_id", 'name', "product_name", 'category', "product_category") end as "product_json" from "origin_query") , "cte_array_depth_1" as (select "product_json" , "sale_id" , "sale_date" , "sale_total" , "product_id" , "product_name" , "product_category" , jsonb_agg(jsonb_build_object('id', "detail_id", 'quantity', "detail_quantity", 'price', "detail_price", 'product', "product_json")) as "details" from "cte_object_depth_1" group by "product_json" , "sale_id" , "sale_date" , "sale_total" , "product_id" , "product_name" , "product_category") , "cte_root_sales" as (select jsonb_build_object('id', "sale_id", 'date', "sale_date", 'total', "sale_total", 'details', "details") as "Sales" from "cte_array_depth_1") select jsonb_agg("Sales") as "Sales_array" from "cte_root_sales"
SQL might not be so bad after all.
Poor Maintainability of Long Queries
DSLs are also quite hard to read when they are long, but the poor maintainability of long SQL is in a league of its own.
To debug CTEs or subqueries, you have to break the SQL structure.
A: I'm sorry!
I just couldn't manage this one.
Summary
Don't you think the issue of "SQL is no good" has been somewhat improved?
Aren't we potentially achieving productivity that surpasses DSLs while maintaining maintainability?
Since SQL's SELECT processing is very efficient, there's originally no reason not to use it.
If we can analyze and manipulate SQL, the possibilities for ORMs will expand!
That's what I believe.
Finally, here is a link to the library introduced in this article. By the way, I am the author.
P.S.
I just couldn't manage this one.
I am currently looking for an answer to this problem. I think I am close to finding it.
Discussion
僕は別解「直接GraphQLをサーバー・言語として使う」を考えました👀
僕もChatGPTの結論の「前述のGraphQL構成ではパフォーマンスチューニングに劣る」に同意していますが、今回の論点である以下には、ひとつの答えとしてもよさそうです!
拙い記事にコメントいただき大変うれしいです。
あいやさんのコメントですが、「GraphQLをDSLとして使用する」と勝手に解釈しました。
「あり」だと思います。
なにせ私もやってることは「SQLをDSLとして使用」しているに過ぎないからです。
ORMのようなことをやろうとすると、
になりがちです。
そのDSLは「ぼくのかんがえたさいきょうのなんたら」なので、ライブラリの思想そのものです。互換性というものはなくて当然。
思想に賛同する方をユーザにつけるという割り切りがあります。
ただ、これは後発組にはハードルが高い。
学習コストが高過ぎるし、未熟なライブラリに賭けるユーザは少ない。
そこで以下のように考えました。
その結果、「DSLとしてSQLが採用された」に過ぎません。
SQLなら何かあってもライブラリを通さなければいいだけですからねw
私もSQLをよく使います!
最後の「長文の保守性が悪い」は、そもそも長文にしないというのはどうでしょうか。
まずはSQL初心者でもすぐに書けるシンプルなCRUDに留めて、それだとどうしてもパフォーマンスが落ちるときだけ長文にするのがいいと思います。
NoSQLで構築されたシステムも沢山あるわけで、どうしても長文にしなければならない場面は滅多に訪れないでしょう。
素晴らしい記事ありがとうございます!Twitterの方でもRTさせていただきました。
自分も過去に似たような記事を書いたことがあります。是非こちらも興味があれば確認してみてください!
記事の紹介ありがとうございます。バックエンド、SQL関係の記事、大変興味があります。
calloc134さんのカテゴリで言えば、私が紹介したライブラリは、「SQL→ コード のアプローチ」にあたります。
そのうえ
rawsql-ts特長を加えさせていただきます。デモサイト https://mk3008.github.io/rawsql-ts/
紹介していただいたライブラリについて想像で語ってしまいますが、RawSQLをパラメータクエリそのものとして扱っているのではないでしょうか?
例文ですと、以下のように書かれておりました。
このパラメータクエリですが、ID検索専用のように見えます。別の用途(たとえば名前検索)には使用できませんので、SQLが乱立しそうな印象を受けました。(もしかしたらSQLコメントを使用した独自構文があるのかも)
一方、rawsql-ts では上記のコードは以下のように書きます。(意味があるかは置いといて)
静的条件は書きますが、動的検索条件は書かないのがポイントです。SQLのAST解析をしているため、1つの汎用的SQLを用意すれば、パラメータ定義に合わせて、以下のような多種多様のSQLを生成可能です。
id, name という列が存在するかどうかは、SQL自身から取得しています(例文はワイルドカードだったのでそこは変えました)。無ければエラー(静的検査可能)になります。ワイルドカードを使用したい場合は、スキーマ情報を引数に渡すことで解析は可能です。どちらの方法を採用するかはライブラリ利用者の裁量という考えです。
また、型安全については、かなり割り切ったアプローチをしています。
列「id」が存在しているかは分かりますが、できるのはそこまでです。列「id」の型が何であるかを把握することはしていません。ただ、SQLにおいては、厳密な型情報というのはそこまで必要ではないのでは、と考えています。なぜなら、SQL(DB)においては型はテーブルにて固定化されており、型情報は暗黙の了解として開発者に認知されていることが多いためです。ここは意見が分かれるところかもしれません。
有用な記事をありがとうございます。
素朴な疑問なのですが、↓のSQL
WITH
cte_users AS (
SELECT
id
, name
FROM
users
WHERE
active = true
AND name = $1
)
SELECT
*
FROM
(
SELECT
id AS user_id
, name AS user_name
FROM
cte_users
WHERE
id = $2
) AS sub
を以下のようにすれば簡潔と思うのですが、そうしない理由はありますか?
WITH
cte_users AS (
SELECT
id AS user_id
, name AS user_name
FROM
users
WHERE
active = true
AND name = $1
)
SELECT
*
FROM
cte_users
WHERE
id = $2
なんならWHEREをくっつけて一文にすることもできそうです。
批判とかでなく、純粋な疑問です。ご教示いただけると幸いです。
ご質問、ありがとうございます。
興味を持っていただけたことが素直にうれしいです。
では、本題のライブラリの機能について説明します。
該当のTypeScriptのコードを要点だけ記述するとこのようになります。
パラメータ合成のもととなる
sqlですが、SQLの記述に縛りがなく、CTEやサブクエリ、ユニオンクエリが使用可能というのがポイントです。次に、パラメータ合成クラス
SqlParamInjectorですが、という仕様で検索条件を合成します。
このため、生成されるSQLは元のSQLに強く依存します。
例文では、一般的には書かないようなSQLを書いています。実践ならば以下のクエリを書くべきです。
これを無駄に複雑に記述(サブクエリとCTEを使い、かつ列名のエイリアスもばらばらに定義)したものがアレです。
あくまで複雑なクエリのメタファー として見ていただければと思います。「複雑である」こと以上の意味はありません。
そしてこのようなサブクエリ、CTEを使用した複雑なクエリは、以下のように階層を解析されます。
複雑なのは
user_idだと思うので、こちらを説明しますと、user_idはlevel1に存在するので、level1のクエリが加工の候補になります。ただし、user_idはサブクエリであるため、上流に定義があるとして、level2が検査対象になります。level2を検査するとuser_idは列エイリアスであることが分かります。列エイリアスの場合、検査を打ち切りしますので、level2がuser_idが定義されている最深部である、と判定され、level2のクエリに検索条件が挿入される。nameも同じ理屈で検査するので、level3のクエリに検索条件が挿入されます。というわけで、サンプルのSQL自体はあまり気になさらず、
CTE、サブクエリ、ユニオンクエリを使用した場合もできるだけ有効な場所にパラメータを挿入してくれる と思っていただけば幸いです。
ライブラリは npm で公開しておりますので、よろしければお試しください。またドキュメントも用意してありますので、よろしければどうぞ。