Skip to content

Commit ea976ac

Browse files
committed
feat(python): keep formatting and indentation of the multiline SQL queries
Part of #26
1 parent 6c05105 commit ea976ac

File tree

3 files changed

+44
-7
lines changed

3 files changed

+44
-7
lines changed

examples/python/routes.py

+26-3
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,14 @@ def get_v1_collections_collection_id_categories_count(collectionId, conn = Depen
5151
try:
5252
with conn:
5353
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
54-
cur.execute("SELECT COUNT(DISTINCT s.category_id) AS counter FROM collections_series cs JOIN series s ON s.id = cs.series_id WHERE cs.collection_id = %(collectionId)s", { "collectionId": collectionId })
54+
cur.execute(
55+
"""
56+
SELECT COUNT(DISTINCT s.category_id) AS counter
57+
FROM collections_series cs
58+
JOIN series s
59+
ON s.id = cs.series_id
60+
WHERE cs.collection_id = %(collectionId)s
61+
""", { "collectionId": collectionId })
5562
result = cur.fetchone()
5663
if result is None:
5764
raise HTTPException(status_code=404)
@@ -64,7 +71,15 @@ def get_list_v1_categories(limit, conn = Depends(db_connection)):
6471
try:
6572
with conn:
6673
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
67-
cur.execute("SELECT id , name , name_ru , slug FROM categories LIMIT %(limit)s", { "limit": limit })
74+
cur.execute(
75+
"""
76+
SELECT id
77+
, name
78+
, name_ru
79+
, slug
80+
FROM categories
81+
LIMIT %(limit)s
82+
""", { "limit": limit })
6883
return cur.fetchall()
6984
finally:
7085
conn.close()
@@ -78,7 +93,15 @@ def get_v1_categories_category_id(categoryId, conn = Depends(db_connection)):
7893
try:
7994
with conn:
8095
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
81-
cur.execute("SELECT id , name , name_ru , slug FROM categories WHERE id = %(categoryId)s", { "categoryId": categoryId })
96+
cur.execute(
97+
"""
98+
SELECT id
99+
, name
100+
, name_ru
101+
, slug
102+
FROM categories
103+
WHERE id = %(categoryId)s
104+
""", { "categoryId": categoryId })
82105
result = cur.fetchone()
83106
if result is None:
84107
raise HTTPException(status_code=404)

src/cli.js

+1
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,7 @@ const createEndpoints = async (destDir, lang, config) => {
243243
},
244244

245245
"placeholdersMap": placeholdersMap,
246+
"removeComments": removeComments,
246247
}
247248
);
248249

src/templates/routes.py.ejs

+17-4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,19 @@ function convertToFastApiPath(path) {
3232
return path.replace(/:([_a-zA-Z]+)/g, '{$1}')
3333
}
3434
35+
// Differs from formatQuery() as it doesn't flatten query (preserve original formatting)
36+
// and also use """ for multiline strings
37+
function formatQueryForPython(query, indentLevel) {
38+
const sql = removePlaceholders(removeComments(query))
39+
const isMultilineSql = sql.indexOf('\n') >= 0
40+
if (isMultilineSql) {
41+
const indent = ' '.repeat(indentLevel)
42+
const indentedSql = sql.replace(/\n/g, '\n' + indent)
43+
return `\n${indent}"""\n${indent}${indentedSql}\n${indent}"""`;
44+
}
45+
return `"${sql}"`
46+
}
47+
3548
3649
endpoints.forEach(function(endpoint) {
3750
const path = convertToFastApiPath(endpoint.path)
@@ -58,7 +71,7 @@ endpoints.forEach(function(endpoint) {
5871
const queries = []
5972
queriesWithNames.forEach(queryWithName => {
6073
for (const [name, query] of Object.entries(queryWithName)) {
61-
const sql = convertToPsycopgNamedArguments(formatQuery(query))
74+
const sql = convertToPsycopgNamedArguments(formatQueryForPython(query, 20))
6275
const params = extractParamsFromQuery(query);
6376
const formattedParams = params.length > 0
6477
// [ "p.categoryId" ] => [ '"categoryId": categoryId' ]
@@ -81,7 +94,7 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
8194
<% queries.forEach(queryInfo => {
8295
for (const [name, query] of Object.entries(queryInfo)) {
8396
-%>
84-
cur.execute("<%- query.sql %>"<%- query.formattedParams %>)
97+
cur.execute(<%- query.sql %><%- query.formattedParams %>)
8598
result['<%- name %>'] = cur.fetchone()[0]
8699
<% }
87100
})
@@ -92,7 +105,7 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
92105
const query = queries[0].result
93106
-%>
94107
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
95-
cur.execute("<%- query.sql %>"<%- query.formattedParams %>)
108+
cur.execute(<%- query.sql %><%- query.formattedParams %>)
96109
result = cur.fetchone()
97110
if result is None:
98111
raise HTTPException(status_code=404)
@@ -102,7 +115,7 @@ def <%- pythonMethodName %>(<%- methodArgs.join(', ') %>):
102115
const query = queries[0].result
103116
-%>
104117
with conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
105-
cur.execute("<%- query.sql %>"<%- query.formattedParams %>)
118+
cur.execute(<%- query.sql %><%- query.formattedParams %>)
106119
return cur.fetchall()
107120
<%
108121
}

0 commit comments

Comments
 (0)