문서 편집 권한이 없습니다. 다음 이유를 확인해주세요:
요청한 명령은 다음 권한을 가진 사용자에게 제한됩니다: 사용자.
== Python sqlparse를 이용한 SQL 포맷팅 == * sqlparse는 Python으로 작성된 강력한 SQL 파싱 및 포맷팅 라이브러리 === 기본 설치 === <source lang=bash> pip install sqlparse </source> === 기본 사용 예제 === 간단한 SQL 포맷팅 <source lang=python> import sqlparse </source> <source lang=python> raw_sql = """ SELECT * FROM users WHERE id=1 ORDER BY name; """ formatted_sql = sqlparse.format(raw_sql, reindent=True, keyword_case='upper') print(formatted_sql) </source> * 출력 결과: <source lang=sql> SELECT * FROM users WHERE id = 1 ORDER BY name; </source> === 고급 포맷팅 옵션 === <source lang=python> import sqlparse sql = """ select u.id,u.name,count(o.id) as order_count from users u left join orders o on u.id=o.user_id where u.status='active' and o.date>='2023-01-01' group by u.id,u.name having count(o.id)>5 order by order_count desc; """ # 다양한 옵션 적용 formatted = sqlparse.format( sql, reindent=True, # 들여쓰기 적용 keyword_case='upper', # 키워드 대문자로 identifier_case='lower', # 식별자 소문자로 strip_comments=True, # 주석 제거 indent_width=4, # 들여쓰기 4칸 comma_first=False, # 콤마 위치 (False: 뒤에, True: 앞에) use_space_around_operators=True # 연산자 주변 공백 ) print(formatted) </source> 출력 결과: <source lang=sql> SELECT u.id, u.name, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.status = 'active' AND o.date >= '2023-01-01' GROUP BY u.id, u.name HAVING COUNT(o.id) > 5 ORDER BY order_count DESC; </source> === SQL 구문 분석 및 수정 === <source lang=python> import sqlparse sql = """ INSERT INTO employees(id,name,dept) VALUES(1,'John','IT'); """ # SQL 파싱 parsed = sqlparse.parse(sql)[0] # 토큰별로 처리 for token in parsed.tokens: if isinstance(token, sqlparse.sql.IdentifierList): # 컬럼 목록을 각 줄에 하나씩 출력 print("Columns:") for col in token.get_identifiers(): print(f"- {col}") elif isinstance(token, sqlparse.sql.Values): # VALUES 절 처리 print("Values:") print(token) # 수정된 SQL 생성 formatted = sqlparse.format( sql, reindent=True, keyword_case='upper', wrap_after=80 # 80자에서 줄 바꿈 ) print("\nFormatted SQL:") print(formatted) </source> === 여러 SQL 문장 처리 === <source lang=python> import sqlparse multi_sql = """ CREATE TABLE users(id INT PRIMARY KEY,name VARCHAR(50)); /* This is a comment */ INSERT INTO users VALUES(1,'Alice'); UPDATE users SET name='Bob' WHERE id=1; """ # 여러 SQL 문장 분리 statements = sqlparse.split(multi_sql) print(f"Found {len(statements)} SQL statements:\n") for i, stmt in enumerate(statements, 1): formatted = sqlparse.format(stmt.strip(), reindent=True, keyword_case='upper') print(f"Statement {i}:") print(formatted) print("-" * 50) </source> === 사용자 정의 포맷팅 함수 === <source lang=python> import sqlparse from sqlparse.tokens import Keyword, Punctuation def custom_format(sql): formatted = [] parsed = sqlparse.parse(sql)[0] for token in parsed.flatten(): if token.ttype is Keyword: formatted.append(token.value.upper()) elif token.ttype is Punctuation and token.value == ',': formatted.append(',\n ') else: formatted.append(str(token)) return ''.join(formatted) sql = "select id,name,age from users where status='active' order by name,age desc" print(custom_format(sql)) </source> 출력 결과: <source lang=sql> SELECT id, name, age FROM users WHERE status='active' ORDER BY name, age DESC </source> === 파일 처리 예제 === <source lang=python> import sqlparse from pathlib import Path def format_sql_file(input_file, output_file): with open(input_file, 'r') as f: raw_sql = f.read() formatted = sqlparse.format( raw_sql, reindent=True, keyword_case='upper', indent_width=2, wrap_after=100 ) with open(output_file, 'w') as f: f.write(formatted) print(f"Formatted SQL saved to {output_file}") # 사용 예 format_sql_file('input.sql', 'output.sql') </source> * 주요 포맷팅 옵션 옵션 설명 기본값 reindent 들여쓰기 재조정 False keyword_case 키워드 대소문자 ('upper', 'lower', None) None identifier_case 식별자 대소문자 None strip_comments 주석 제거 False indent_width 들여쓰기 공백 수 2 wrap_after 줄 바꿈할 문자 수 0 (해제) comma_first 콤마 위치 (True: 다음 줄 시작) False sqlparse는 SQL 문법을 이해하는 강력한 라이브러리로, 단순한 포맷팅부터 복잡한 SQL 분석까지 다양한 용도로 사용할 수 있습니다. [[category:python]]
문서 저장 미리 보기 차이 보기 취소