如何从Azure DevOps Git的JSON文件中提取格式化SQL查询?
解决Synapse Serverless Git旧版本SQL脚本JSON转格式化SQL的内置方法
方法1:Synapse Studio直接查看历史版本
如果你的SQL脚本是在Synapse Studio中管理并同步到Azure DevOps Git的,直接在Synapse Studio里操作最简便:
- 打开对应的SQL脚本文件
- 点击顶部菜单栏的历史记录按钮(开启Git集成后可见)
- 在历史版本列表中选择需要查看的旧版本,此时会直接展示格式化后的SQL内容,无需处理JSON文件
方法2:Azure DevOps Git网页端直接解析
无需下载JSON文件,在Azure DevOps网页端即可提取并格式化SQL:
- 打开目标JSON文件的旧版本页面
- 点击页面右上角的Raw按钮,进入原始JSON内容页面
- 按下
F12打开浏览器开发者工具,切换到控制台标签 - 输入以下代码并执行,页面会新增一个包含格式化SQL的可复制区块:
fetch(document.URL) .then(res => res.json()) .then(data => { const sql = data.properties.content.query.replace(/\\n/g, '\n').replace(/\\r/g, '\r'); const pre = document.createElement('pre'); pre.style.cssText = 'position:fixed; top:20px; right:20px; background:white; padding:15px; border:1px solid #ccc; z-index:9999;'; pre.textContent = sql; document.body.appendChild(pre); })
方法3:用Azure CLI/PowerShell直接提取
使用Azure官方工具链,无需依赖Python,直接从命令行获取格式化后的SQL:
Azure CLI(需提前安装并登录)
# 替换为你的组织、项目、仓库、文件路径和提交ID az repos item show --organization https://dev.azure.com/<你的组织名> --project <项目名> --repository <仓库名> --path /<JSON文件路径> --version <旧版本提交ID> --output json | jq '.properties.content.query' | sed 's/\\n/\n/g; s/\\r/\r/g'
PowerShell(Windows自带,无需额外安装)
# 替换为你的组织、项目、仓库ID、文件路径和提交ID $apiUrl = "https://dev.azure.com/<你的组织名>/<项目名>/_apis/git/repositories/<仓库ID>/items?path=/<JSON文件路径>&versionDescriptor.version=<旧版本提交ID>&api-version=7.1-preview.1" $jsonContent = Invoke-RestMethod -Uri $apiUrl -UseDefaultCredentials $sql = $jsonContent.properties.content.query -replace '\\n', "`n" -replace '\\r', "`r" Write-Host $sql
补充:本地Python处理方案
如果需要批量处理或离线操作,你的Python脚本可继续使用,这里贴出方便参考:
import json import sqlparse # Load the JSON file with open(r"C:\YourPathToFile\TheFile.json") as f: data = json.load(f) # Extract the SQL code from the JSON data sql_code = data['properties']['content']['query'] # Replace the newline and carriage return characters sql_code = sql_code.replace('\\n', '\n').replace('\\r', '\r') # Format the SQL code formatted_sql = sqlparse.format(sql_code, reindent=True, keyword_case='upper') # Print the formatted SQL code print(formatted_sql)
内容的提问来源于stack exchange,提问作者Pingyao
相关产品推荐
相关产品推荐

