Skip to content

Commit 69507fa

Browse files
Shun7shout-star
authored andcommitted
Optimized the options and implemented the reserved_case option (#6)
* 予約語のみ大文字に変換するオプションを追加。 ▽変更内容  ・README(英語、日本語)  ・プログラム本体(init.py, api.py, config.py, filters.py)  ・Sublime向け対応としてPreferences.sublime-settingsを改修 * オプション構成の最適化を実施。 * コード修正に伴い、Readmeも修正。 * Readmeを修正。 * sublimeプラグイン実行時に不具合があったので修正。 * Change the default settings of the reserved words option to ANSI SQL(SQL:2011). * Added the 'nochange' option. * Updated the readme files based on the functional update which I made before. * Deleted the blank line. * Changed the default setting of the "uf_case". The default will be "upper" * Added a code to manage backward compatibility. * - fixed the problem with the execution timing of backward compatible code - fixed the problem that the `uf_reserved_words` setting refers only to the user setting * update readme
1 parent fa29c6b commit 69507fa

File tree

8 files changed

+227
-65
lines changed

8 files changed

+227
-65
lines changed

Preferences.sublime-settings

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
{
22
"uf_tab_size": 4,
33
"uf_translate_tabs_to_spaces": true,
4-
"uf_uppercase": true,
4+
"uf_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
5+
// You have to set [uf_case]option,
6+
// when you set [uf_reserved_case]option below.
7+
// The applocation does not accept the reserved_case option individually.
8+
"uf_reserved_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
9+
"uf_reserved_words":"ABS,ALL,ALLOCATE,ALTER,AND,ANY,ARE,ARRAY,ARRAY_AGG,ARRAY_MAX_CARDINALITY,AS,ASENSITIVE,ASYMMETRIC,AT,ATOMIC,AUTHORIZATION,AVG,BEGIN,BEGIN_FRAME,BEGIN_PARTITION,BETWEEN,BIGINT,BINARY,BLOB,BOOLEAN,BOTH,BY,CALL,CALLED,CARDINALITY,CASCADED,CASE,CAST,CEIL,CEILING,CHAR,CHARACTER,CHARACTER_LENGTH,CHAR_LENGTH,CHECK,CLOB,CLOSE,COALESCE,COLLATE,COLLECT,COLUMN,COMMIT,CONDITION,CONNECT,CONSTRAINT,CONTAINS,CONVERT,CORR,CORRESPONDING,COUNT,COVAR_POP,COVAR_SAMP,CREATE,CROSS,CUBE,CUME_DIST,CURRENT,CURRENT_CATALOG,CURRENT_DATE,CURRENT_DEFAULT_TRANSFORM_GROUP,CURRENT_PATH,CURRENT_ROLE,CURRENT_ROW,CURRENT_SCHEMA,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_TRANSFORM_GROUP_FOR_TYPE,CURRENT_USER,CURSOR,CYCLE,DATALINK,DATE,DAY,DEALLOCATE,DEC,DECIMAL,DECLARE,DEFAULT,DELETE,DENSE_RANK,DEREF,DESCRIBE,DETERMINISTIC,DISCONNECT,DISTINCT,DLNEWCOPY,DLPREVIOUSCOPY,DLURLCOMPLETE,DLURLCOMPLETEONLY,DLURLCOMPLETEWRITE,DLURLPATH,DLURLPATHONLY,DLURLPATHWRITE,DLURLSCHEME,DLURLSERVER,DLVALUE,DOUBLE,DROP,DYNAMIC,EACH,ELEMENT,ELSE,END,END-EXEC,END_FRAME,END_PARTITION,EQUALS,ESCAPE,EVERY,EXCEPT,EXEC,EXECUTE,EXISTS,EXP,EXTERNAL,EXTRACT,FALSE,FETCH,FILTER,FIRST_VALUE,FLOAT,FLOOR,FOR,FOREIGN,FRAME_ROW,FREE,FROM,FULL,FUNCTION,FUSION,GET,GLOBAL,GRANT,GROUP,GROUPING,GROUPS,HAVING,HOLD,HOUR,IDENTITY,IMPORT,IN,INDICATOR,INNER,INOUT,INSENSITIVE,INSERT,INT,INTEGER,INTERSECT,INTERSECTION,INTERVAL,INTO,IS,JOIN,LAG,LANGUAGE,LARGE,LAST_VALUE,LATERAL,LEAD,LEADING,LEFT,LIKE,LIKE_REGEX,LN,LOCAL,LOCALTIME,LOCALTIMESTAMP,LOWER,MATCH,MAX,MEMBER,MERGE,METHOD,MIN,MINUTE,MOD,MODIFIES,MODULE,MONTH,MULTISET,NATIONAL,NATURAL,NCHAR,NCLOB,NEW,NO,NONE,NORMALIZE,NOT,NTH_VALUE,NTILE,NULL,NULLIF,NUMERIC,OCCURRENCES_REGEX,OCTET_LENGTH,OF,OFFSET,OLD,ON,ONLY,OPEN,OR,ORDER,OUT,OUTER,OVER,OVERLAPS,OVERLAY,PARAMETER,PARTITION,PERCENT,PERCENTILE_CONT,PERCENTILE_DISC,PERCENT_RANK,PERIOD,PORTION,POSITION,POSITION_REGEX,POWER,PRECEDES,PRECISION,PREPARE,PRIMARY,PROCEDURE,RANGE,RANK,READS,REAL,RECURSIVE,REF,REFERENCES,REFERENCING,REGR_AVGX,REGR_AVGY,REGR_COUNT,REGR_INTERCEPT,REGR_R2,REGR_SLOPE,REGR_SXX,REGR_SXY,REGR_SYY,RELEASE,RESULT,RETURN,RETURNS,REVOKE,RIGHT,ROLLBACK,ROLLUP,ROW,ROWS,ROW_NUMBER,SAVEPOINT,SCOPE,SCROLL,SEARCH,SECOND,SELECT,SENSITIVE,SESSION_USER,SET,SIMILAR,SMALLINT,SOME,SPECIFIC,SPECIFICTYPE,SQL,SQLEXCEPTION,SQLSTATE,SQLWARNING,SQRT,START,STATIC,STDDEV_POP,STDDEV_SAMP,SUBMULTISET,SUBSTRING,SUBSTRING_REGEX,SUCCEEDS,SUM,SYMMETRIC,SYSTEM,SYSTEM_TIME,SYSTEM_USER,TABLE,TABLESAMPLE,THEN,TIME,TIMESTAMP,TIMEZONE_HOUR,TIMEZONE_MINUTE,TO,TRAILING,TRANSLATE,TRANSLATE_REGEX,TRANSLATION,TREAT,TRIGGER,TRIM,TRIM_ARRAY,TRUE,TRUNCATE,UESCAPE,UNION,UNIQUE,UNKNOWN,UNNEST,UPDATE,UPPER,USER,USING,VALUE,VALUES,VALUE_OF,VARBINARY,VARCHAR,VARYING,VAR_POP,VAR_SAMP,VERSIONING,WHEN,WHENEVER,WHERE,WIDTH_BUCKET,WINDOW,WITH,WITHIN,WITHOUT,XML,XMLAGG,XMLATTRIBUTES,XMLBINARY,XMLCAST,XMLCOMMENT,XMLCONCAT,XMLDOCUMENT,XMLELEMENT,XMLEXISTS,XMLFOREST,XMLITERATE,XMLNAMESPACES,XMLPARSE,XMLPI,XMLQUERY,XMLSERIALIZE,XMLTABLE,XMLTEXT,XMLVALIDATE,YEAR",
510
"uf_comment_syntax": "uroboroSQL", // "uroboroSQL" or "doma2"
611
"uf_escapesequence_u005c": false,
712
"uf_save_on_format": false,

Readme.ja.md

+25-17
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
uroboroSQL Formatter
1+
Sublime uroboroSQL Formatter
22
====================
33

4-
uroboroSQL Formatterは、エンタープライズシステムで用いられることの多い、
4+
[![Package Control](https://img.shields.io/packagecontrol/dt/uroboroSQL%20Formatter.svg)](https://packagecontrol.io/packages/uroboroSQL%20Formatter)
5+
6+
Sublime uroboroSQL Formatterは、エンタープライズシステムで用いられることの多い、
57
非常に長いSQL(1K step以上)でも見やすく保守性の高いスタイルへフォーマットするための
68
Sublime Text 3のプラグインです。
79

@@ -25,7 +27,7 @@ WHERE 1 = 1
2527
AND MI.ARRIVAL_DATE = '2016-12-01' -- 入荷日
2628
```
2729

28-
#### uroboroSQL Formatterの場合
30+
#### Sublime uroboroSQL Formatterの場合
2931

3032
```sql
3133
SELECT
@@ -62,7 +64,9 @@ Settings
6264
{
6365
"uf_tab_size": 4,
6466
"uf_translate_tabs_to_spaces": true,
65-
"uf_uppercase": true,
67+
"uf_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
68+
"uf_reserved_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
69+
"uf_reserved_words":"SELECT, FROM, WHERE, CREATE" // Put commas to separate reserved words
6670
"uf_comment_syntax": "uroboroSQL", // "uroboroSQL" or "doma2"
6771
"uf_escapesequence_u005c": false,
6872
"uf_save_on_format": true,
@@ -74,18 +78,22 @@ Settings
7478
- フォーマット後のインデントのタブサイズを指定します。4つを推奨します。
7579
- uf_translate_tabs_to_spaces
7680
- フォーマット後のインデントをタブにするかスペースにするかを指定します。trueにすることでスペースになります。
77-
- uf_uppercase
78-
- 予約語と識別子を大文字に変換する場合はtrueを指定します。
79-
- uf_comment_syntax
80-
- コメントのシンタックス形式を指定します。
81-
- 「uroboroSQL」または「doma2」の指定が可能です。
82-
- 通常のSQLの場合は、どちらを指定してもかまいません。
83-
- uf_escapesequence_u005c
84-
- SQL内でエスケープシーケンスをバックスラッシュで指定している場合にtrueを指定します。
85-
- uf_save_on_format
86-
- ファイル保存時に自動的にフォーマットする場合にtrueを指定します。
87-
- uf_save_on_format_extensions
88-
- フォーマットするファイルの拡張子をリストで指定します。
81+
- uf_case
82+
- 全ての文字(予約語と識別子等全て)を指定のケース(大文字、小文字、文頭大文字、変換しない)に変換する時に使用する。
83+
- uf_reserved_case
84+
- 予約語を指定のケース(大文字、小文字、文頭大文字)に変換する時に使用する。なお、"nochange"オプションを指定した場合は予約語に限ったケース変換はせず、全てのケースを「uf_case」に従って変換する。
85+
- uf_reserved_words
86+
- 予約語のみをケース変換したい場合は、「uf_reserved_case」に指定のケース(upper, lower, capitalize or nochange)を設定するとともに、当項目に予約語のリストをカンマ区切りで指定します。
87+
- uf_comment_syntax
88+
- コメントのシンタックス形式を指定します。
89+
- 「uroboroSQL」または「doma2」の指定が可能です。
90+
- 通常のSQLの場合は、どちらを指定してもかまいません。
91+
- uf_escapesequence_u005c
92+
- SQL内でエスケープシーケンスをバックスラッシュで指定している場合にtrueを指定します。
93+
- uf_save_on_format
94+
- ファイル保存時に自動的にフォーマットする場合にtrueを指定します。
95+
- uf_save_on_format_extensions
96+
- フォーマットするファイルの拡張子をリストで指定します。
8997

9098

9199
License
@@ -95,4 +103,4 @@ License
95103

96104
---
97105

98-
Copyright 2017 by Future Architect.
106+
Copyright 2018 by Future Architect.

Readme.md

+37-29
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
uroboroSQL Formatter
1+
Sublime uroboroSQL Formatter
22
====================
33

4-
UroboroSQL Formatter is often used in enterprise systems, For formatting to a highly maintainable style even for very long SQL (1 K step or more) It is a plug-in of Sublime Text 3.
4+
[![Package Control](https://img.shields.io/packagecontrol/dt/uroboroSQL%20Formatter.svg)](https://packagecontrol.io/packages/uroboroSQL%20Formatter)
5+
6+
Sublime uroboroSQL Formatter is often used in enterprise systems, For formatting to a highly maintainable style even for very long SQL (1 K step or more) It is a plug-in of Sublime Text 3.
57

68
In particular, in countries where English is not their mother tongue, such as Japan, comments may be included in SELECT clauses. In that case, we will align the vertical position of the AS clause and the comment, pursuing the viewability which can be said as artistic anymore, This was developed to realize this automatically.
79

@@ -10,32 +12,32 @@ for Japanese, [Readme.ja.md](Readme.ja.md)
1012
#### In case of general formatter
1113

1214
```sql
13-
SELECT MI.MAKER_CD AS ITEM_MAKER_CD -- メーカーコード
15+
SELECT MI.MAKER_CD AS ITEM_MAKER_CD -- maker code
1416
,
15-
MI.BRAND_CD AS ITEM_BRAND_CD -- ブランドコード
17+
MI.BRAND_CD AS ITEM_BRAND_CD -- brand code
1618
,
17-
MI.ITEM_CD AS ITEM_CD -- 商品コード
19+
MI.ITEM_CD AS ITEM_CD -- item code
1820
,
19-
MI.CATEGORY AS ITEM_CATEGORY -- 商品カテゴリ
20-
FROM M_ITEM MI -- 商品マスタ
21+
MI.CATEGORY AS ITEM_CATEGORY -- item category
22+
FROM M_ITEM MI -- item master
2123

2224
WHERE 1 = 1
23-
AND MI.ARRIVAL_DATE = '2016-12-01' -- 入荷日
25+
AND MI.ARRIVAL_DATE = '2016-12-01' -- arrival date
2426
```
2527

26-
#### In case of uroboroSQL Formatter
28+
#### In case of Sublime uroboroSQL Formatter
2729

2830
```sql
2931
SELECT
30-
MI.MAKER_CD AS ITEM_MAKER_CD -- メーカーコード
31-
, MI.BRAND_CD AS ITEM_BRAND_CD -- ブランドコード
32-
, MI.ITEM_CD AS ITEM_CD -- 商品コード
33-
, MI.CATEGORY AS ITEM_CATEGORY -- 商品カテゴリ
32+
MI.MAKER_CD AS ITEM_MAKER_CD -- maker code
33+
, MI.BRAND_CD AS ITEM_BRAND_CD -- brand code
34+
, MI.ITEM_CD AS ITEM_CD -- item code
35+
, MI.CATEGORY AS ITEM_CATEGORY -- item category
3436
FROM
35-
M_ITEM MI -- 商品マスタ
37+
M_ITEM MI -- item master
3638
WHERE
3739
1 = 1
38-
AND MI.ARRIVAL_DATE = '2016-12-01' -- 入荷日
40+
AND MI.ARRIVAL_DATE = '2016-12-01' -- arrival date
3941

4042
```
4143

@@ -60,7 +62,9 @@ Settings
6062
{
6163
"uf_tab_size": 4,
6264
"uf_translate_tabs_to_spaces": true,
63-
"uf_uppercase": true,
65+
"uf_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
66+
"uf_reserved_case": "upper", // "upper" or "lower" or "capitalize" or "nochange"
67+
"uf_reserved_words":"SELECT, FROM, WHERE, CREATE" // Put commas to separate reserved words
6468
"uf_comment_syntax": "uroboroSQL", // "uroboroSQL" or "doma2"
6569
"uf_escapesequence_u005c": false,
6670
"uf_save_on_format": true,
@@ -72,18 +76,22 @@ Settings
7276
- Specify the tab size of the indent after formatting. We recommend 4.
7377
- uf_translate_tabs_to_spaces
7478
- Specify whether the indent after formatting is tab or space. It becomes a space by setting it to true.
75-
- uf_uppercase
76-
- If you want to convert a reserved word and identifier to uppercase specifies true.
77-
- uf_comment_syntax
78-
- It specifies the comment syntax format.
79-
- You can specify the "uroboroSQL" or "doma2".
80-
- In the case of normal SQL, you can specify either.
81-
- uf_escapesequence_u005c
82-
- If you have specified the escape sequence with a backslash in the SQL to specify the true.
83-
- uf_save_on_format
84-
- Specify true when formatting automatically when saving files.
85-
- uf_save_on_format_extensions
86-
- Specify the extension of the file to be formatted in a list.
79+
- uf_case
80+
- If you want to convert all words to a specific case, set "upper", "lower", "capitalize". If the "nochange" option is selected, the word cases will not be changed from the original.
81+
- uf_reserved_case
82+
- If you want to convert reserved words to a specific case, set "upper", "lower" or "capitalize". If the "nochange" option is selected, it will not change the cases of resered words and they will be changed based on the "uf_case" setting.
83+
- uf_reserved_words
84+
- If you want to convert only reserved words to a specific case, please input reserved words sepalated by a comma. (The input is not case sensitive. So you can input reserved words in any case.)
85+
- uf_comment_syntax
86+
- It specifies the comment syntax format.
87+
- You can specify the "uroboroSQL" or "doma2".
88+
- In the case of normal SQL, you can specify either.
89+
- uf_escapesequence_u005c
90+
- If you have specified the escape sequence with a backslash in the SQL to specify the true.
91+
- uf_save_on_format
92+
- Specify true when formatting automatically when saving files.
93+
- uf_save_on_format_extensions
94+
- Specify the extension of the file to be formatted in a list.
8795

8896
License
8997
-------
@@ -92,4 +100,4 @@ License
92100

93101
---
94102

95-
Copyright 2017 by Future Architect.
103+
Copyright 2018 by Future Architect.

uroborosqlfmt/__init__.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,12 @@ def format_sql(sql, local_config = config.LocalConfig()):
7777
stack = sqlparse.engine.FilterStack()
7878
stack.enable_grouping()
7979

80-
if local_config.uppercase:
81-
stack.preprocess.append(sqlparse.filters.KeywordCaseFilter())
82-
stack.preprocess.append(sqlparse.filters.IdentifierCaseFilter())
80+
if local_config.case != None:
81+
stack.preprocess.append(sqlparse.filters.KeywordCaseFilter(local_config.case))
82+
stack.preprocess.append(sqlparse.filters.IdentifierCaseFilter(local_config.case))
83+
84+
if local_config.reserved_case != None:
85+
stack.preprocess.append(filters.ReservedWordCaseFilter(local_config))
8386

8487
stack.stmtprocess.append(filters.GroupFilter())
8588
stack.stmtprocess.append(filters.LineDescriptionLineCommentFilter(local_config))

uroborosqlfmt/api.py

+58-8
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,17 @@ def _parse_args(test_args=None):
141141
choices=['file', 'directory'], \
142142
help='format target. default "file"', \
143143
)
144-
145-
parser.add_argument('-N', '--nochange_case', \
146-
action='store_true', \
147-
help='UPPERCASE off.', \
144+
parser.add_argument('-a', '--case', \
145+
action='store', \
146+
default=None, \
147+
type=str, \
148+
choices=['upper', 'lower', 'capitalize'], \
149+
)
150+
parser.add_argument('-e', '--reserved_case', \
151+
action='store', \
152+
default=None, \
153+
type=str, \
154+
choices=['upper', 'lower', 'capitalize'], \
148155
)
149156
parser.add_argument('-B', '--escapesequence_u005c', \
150157
action='store_true', \
@@ -157,6 +164,12 @@ def _parse_args(test_args=None):
157164
choices=['uroborosql', 'doma2', 'uroboro', 'doma'], \
158165
help='SQL comment out syntax type.', \
159166
)
167+
parser.add_argument('-r', '--reserved_words_file_path', \
168+
action='store', \
169+
default=None, \
170+
type=str, \
171+
help='input reserved words file path.', \
172+
)
160173

161174
return parser.parse_args(test_args)
162175

@@ -171,16 +184,20 @@ def __execute():
171184
args = _parse_args()
172185

173186
mode = args.mode
174-
nochange_case = args.nochange_case
187+
case = args.case
188+
reserved_case = args.reserved_case
175189
escapesequence_u005c = args.escapesequence_u005c
176190
comment_syntax = args.comment_syntax
177191
input_path = args.input_path
178192
output_path = args.output_path
193+
reserved_words_file_path = args.reserved_words_file_path
179194
local_config = LocalConfig()
180195

181-
set_uppercase(local_config, not nochange_case)
196+
set_case(local_config, case)
197+
set_reserved_case(local_config, reserved_case)
182198
set_escapesequence_u005c(escapesequence_u005c)
183199
set_comment_syntax(local_config, comment_syntax)
200+
set_reserved_words(local_config, reserved_words_file_path)
184201

185202
"""
186203
The application requires either "file" or "directory"
@@ -199,8 +216,18 @@ def __execute():
199216
print("===== End =====")
200217

201218

202-
def set_uppercase(local_config, uppercase):
203-
local_config.set_uppercase(uppercase)
219+
def set_case(local_config, case):
220+
local_config.set_case(case)
221+
222+
223+
def set_reserved_case(local_config, reserved_case):
224+
if local_config.case == None and local_config.reserved_case != None:
225+
print ("You have to set [case(-a)]option, "\
226+
"when you set [reserved_case(-e)]option.\n" \
227+
"The applocation does not accept the reserved_case option individually.")
228+
sys.exit("Application quitting...")
229+
else:
230+
local_config.set_reserved_case(reserved_case)
204231

205232

206233
def set_escapesequence_u005c(escapesequence_u005c):
@@ -215,5 +242,28 @@ def set_comment_syntax(local_config, comment_syntax):
215242
else:
216243
sys.exit()
217244

245+
246+
def set_reserved_words(local_config, reserved_words_file):
247+
if reserved_words_file is not None:
248+
try:
249+
f = open(reserved_words_file, 'r')
250+
lines = f.readlines()
251+
f.close()
252+
except IOError:
253+
print("File I/O error: %s" % reserved_words_file)
254+
print("Please check the file path.")
255+
sys.exit("Application quitting...")
256+
except:
257+
print ("Unexpected error:", sys.exc_info()[0])
258+
sys.exit("Application quitting...")
259+
else:
260+
reserved_words = []
261+
262+
for line in lines:
263+
reserved_words.append(line.rstrip('\n').lower()) # Eliminate newline code.
264+
265+
local_config.set_input_reserved_words(reserved_words)
266+
267+
218268
if __name__ == "__main__":
219269
__execute()

uroborosqlfmt/config.py

+14-4
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,28 @@ def set_escape_sequence_u005c(self, escape_sequence):
1616

1717
class LocalConfig(object):
1818

19-
__slots__ = ('comment_syntax', 'uppercase')
19+
__slots__ = ('comment_syntax', 'case', 'reserved_case','input_reserved_words')
2020

2121
def __init__(self):
2222
self.comment_syntax = UroboroSqlCommentSyntax()
23-
self.uppercase = True
23+
self.case = None
24+
self.reserved_case = None
25+
self.input_reserved_words = None
2426

2527
def set_commentsyntax(self, comment_syntax):
2628
self.comment_syntax = comment_syntax
2729
return self
2830

29-
def set_uppercase(self, uppercase):
30-
self.uppercase = uppercase
31+
def set_case(self, case):
32+
self.case = case
33+
return self
34+
35+
def set_reserved_case(self, reserved_case):
36+
self.reserved_case = reserved_case
37+
return self
38+
39+
def set_input_reserved_words(self, input_reserved_words):
40+
self.input_reserved_words = input_reserved_words
3141
return self
3242

3343

0 commit comments

Comments
 (0)