(Day 83 of 100) Final Puzzle Piece: GraphQL Meets SQL
The ah-ha moment came when I finally understood that GraphQL queries and mutations don’t actually create queries and mutations themselves from the database. Instead, GraphQL wraps SQL commands and serves that as an API to the front-end. I couldn’t easily gain this simple conceptual understanding for a long time because SQL statements were hidden under Django ORM code layer and nobody really delves into the SQL statements in the full-stack tutorial videos as if SQL is a dark magic. The below code explains all.
“but what is the connection between GraphQL and SQL? ” was the question that was stuck in my head and had been a constant bother. An accidental stumble upon an article How to Perform Raw SQL Queries in Django by Ather Rashid made everything come into senses.
[Update 4/19/2019] However, note that using raw SQL commands directly on django will pose a security threat as user can perform SQL injection attack. So, when you can, always try to use Django ORM. Below is an example of SQL injection attack.
>>> user_input = '" OR 1 = 1--'
>>> query = f'SELECT * FROM Customers WHERE CustomerName = "{user_input}"'
>>> query 'SELECT * FROM Customers WHERE CustomerName = '""OR 1=1--"'Result: Every customer in the database will be selected because 1=1 is always trueHow can you Protect yourself from it?
1. Never trust user input
2. validate it with django forms
- be as strict as possible with the valid characters
- be strict as possible since malicious input relies on special characters
3. avoid writing manual SQL queries (use the Django ORM)