feat: SQL 提交前自动格式化(sqlparse)

- format_code 新增 sql 分支,reindent + 关键字大写
- FormatCodeSerializer 的 language choices 加入 sql

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 10:05:38 -06:00
parent 2ec036ac37
commit 16ec78beae
2 changed files with 11 additions and 2 deletions

View File

@@ -123,4 +123,4 @@ class SubmissionListSerializer(serializers.ModelSerializer):
class FormatCodeSerializer(serializers.Serializer): class FormatCodeSerializer(serializers.Serializer):
code = serializers.CharField(max_length=1024 * 1024) code = serializers.CharField(max_length=1024 * 1024)
language = serializers.ChoiceField(choices=("python", "c", "cpp")) language = serializers.ChoiceField(choices=("python", "c", "cpp", "sql"))

View File

@@ -1,5 +1,7 @@
import subprocess import subprocess
import sqlparse
CLANG_FORMAT_STYLE = "{BasedOnStyle: LLVM, IndentWidth: 4, BreakBeforeBraces: Attach}" CLANG_FORMAT_STYLE = "{BasedOnStyle: LLVM, IndentWidth: 4, BreakBeforeBraces: Attach}"
@@ -14,16 +16,23 @@ class FormatToolError(Exception):
def format_code(code, language): def format_code(code, language):
""" """
:param code: 用户代码 :param code: 用户代码
:param language: "python" | "c" | "cpp" :param language: "python" | "c" | "cpp" | "sql"
:return: 格式化后的代码字符串 :return: 格式化后的代码字符串
:raises FormatSyntaxError: 代码语法错误导致格式化失败(仅 python :raises FormatSyntaxError: 代码语法错误导致格式化失败(仅 python
:raises FormatToolError: 格式化工具本身执行失败 :raises FormatToolError: 格式化工具本身执行失败
""" """
if language == "python": if language == "python":
return _format_with_ruff(code) return _format_with_ruff(code)
if language == "sql":
return _format_with_sql(code)
return _format_with_clang(code, language) return _format_with_clang(code, language)
def _format_with_sql(code):
# sqlparse 对语法错误宽容,不会抛异常,语法问题留给判题阶段反馈
return sqlparse.format(code, reindent=True, keyword_case="upper")
def _format_with_ruff(code): def _format_with_ruff(code):
try: try:
result = subprocess.run( result = subprocess.run(