9. ネストした佩は卦せなくo
い
SQL に JSON をMむv方がある
SELECT u.id, u.name, json_agg(c.content) as comments
FROM users AS u
LEFT OUTER JOIN comments AS c ON u.id = user_id
GROUP BY 1, 2
10. Array 秘りの JSON の箭
curl -X GET
-H 'Authorization: Token 4f3326a4-b900-4624-af58-87e8f363dee6'
-F "haute_couture[query]=
SELECT u.id, u.name, json_agg(c.content) as comments
FROM users AS u
LEFT OUTER JOIN comments AS c ON u.id = user_id
GROUP BY 1, 2"
https://sqlql-sample-yancya.herokuapp.com/haute_couture
11. Array 秘りの JSON の箭
[{"id":11,"name":"testuser","comments":["it is not secret"]},
{"id":14,"name":"secretman","comments":[null]},
{"id":10,"name":"yancya","comments":["hoge", "fuga", "piyo"]}]
12. どうやってgFしているのか
リクエストのクエリを CTE(WITH)
の嶄に托めzんでいる
module HauteCouture
def self.find_by_sql(query:, user:)
ActiveRecord::Base.connection.execute(<<~SQL).first['result'] || '[]'
WITH users AS (#{user.for_haute_couture_sql})
, comments AS (#{Comment.for_haute_couture(user).to_sql})
, t AS (#{query})
SELECT JSON_AGG(t) AS result FROM t
SQL
end
end
14. 恷K議にMまれる SQL
WITH users AS (
SELECT "users"."id", "users"."name", "users"."created_at", "users"."updated_at"
FROM "users" WHERE ("users"."id" = 10 OR "users"."privacy" = 'f'))
, t AS (SELECT id, name FROM users) -- <- ここに秘ってるのかリクエストされた SQL
SELECT JSON_AGG(t) AS result FROM t
16. SQL インジェクションで棒
ぬのでは
_かに、likes が畠しされる
SQL になってしまう
WITH users AS (
SELECT "users"."id", "users"."name", "users"."created_at", "users"."updated_at"
FROM "users" WHERE ("users"."id" = 10 OR "users"."privacy" = 'f'))
, t AS (SELECT 1), killer AS (DELETE FROM likes CASCADE RETURNING *)
SELECT JSON_AGG(t) AS result FROM t
17. SQL インジェクションで棒
ぬのでは
送墳に、匯指 SQL パ`サ`に个
せる駅勣がある
PgQuery.parse("SELECT 1), killer AS (DELETE FROM likes CASCADE RETURNING *")
#=> PgQuery::ParseError: syntax error at or near ")" (scan.l:1121)
21. replica 奉來のコネクション
SQLQL のI尖をするときだけ
replica 奉來のコネクションを聞
えば、Mutations っぽい SQL は
Rails が、い討れて宴旋っぽい
ActiveRecord::Base.connected_to(database: :readonly) do
User.first.update(name: 'hoge')
end
#=> ActiveRecord::ReadOnlyError
#=> (Write query attempted while in readonly mode...
22. WITH は裡ないらしい
CTE の WITH 鞘は Rails 議には
ホワイトリストに秘ってないっ
ぽい´´
なぜ WITH がホワイトでないかにつ
いてはLくなるので護曚靴泙坑
になる繁はいて和さい
ActiveRecord::Base.connected_to(database: :readonly) do
ActiveRecord::Base.connection.execute(
"WITH t AS (SELECT 1 AS n) SELECT * FROM t"
)
end
#=> ActiveRecord::ReadOnlyError
#=> (Write query attempted while in readonly mode...
23. DB ユ`ザ`の慙
せっかく}方 DB C嬬があるん
だから、云輝に READONLY な
ユ`ザ`を恬って聞えばよい
create user readonlyuser with password 'readonlyuser' NOCREATEDB NOCREATEROLE;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "readonlyuser";
25. SQLQL の巌樋來
Generated Record Bomb
SELECT generate_series(1, 100000000) AS death
Recurring Nightmare
WITH RECURSIVE r AS (
SELECT 1 AS n UNION ALL SELECT n + 1 AS n FROM r)
SELECT * FROM r