github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/go-xorm/xorm/postgres_dialect.go (about)

     1  // Copyright 2015 The Xorm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package xorm
     6  
     7  import (
     8  	"fmt"
     9  	"strconv"
    10  	"strings"
    11  
    12  	"github.com/insionng/yougam/libraries/go-xorm/core"
    13  )
    14  
    15  // from http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html
    16  var (
    17  	postgresReservedWords = map[string]bool{
    18  		"A":                     true,
    19  		"ABORT":                 true,
    20  		"ABS":                   true,
    21  		"ABSENT":                true,
    22  		"ABSOLUTE":              true,
    23  		"ACCESS":                true,
    24  		"ACCORDING":             true,
    25  		"ACTION":                true,
    26  		"ADA":                   true,
    27  		"ADD":                   true,
    28  		"ADMIN":                 true,
    29  		"AFTER":                 true,
    30  		"AGGREGATE":             true,
    31  		"ALL":                   true,
    32  		"ALLOCATE":              true,
    33  		"ALSO":                  true,
    34  		"ALTER":                 true,
    35  		"ALWAYS":                true,
    36  		"ANALYSE":               true,
    37  		"ANALYZE":               true,
    38  		"AND":                   true,
    39  		"ANY":                   true,
    40  		"ARE":                   true,
    41  		"ARRAY":                 true,
    42  		"ARRAY_AGG":             true,
    43  		"ARRAY_MAX_CARDINALITY": true,
    44  		"AS":                               true,
    45  		"ASC":                              true,
    46  		"ASENSITIVE":                       true,
    47  		"ASSERTION":                        true,
    48  		"ASSIGNMENT":                       true,
    49  		"ASYMMETRIC":                       true,
    50  		"AT":                               true,
    51  		"ATOMIC":                           true,
    52  		"ATTRIBUTE":                        true,
    53  		"ATTRIBUTES":                       true,
    54  		"AUTHORIZATION":                    true,
    55  		"AVG":                              true,
    56  		"BACKWARD":                         true,
    57  		"BASE64":                           true,
    58  		"BEFORE":                           true,
    59  		"BEGIN":                            true,
    60  		"BEGIN_FRAME":                      true,
    61  		"BEGIN_PARTITION":                  true,
    62  		"BERNOULLI":                        true,
    63  		"BETWEEN":                          true,
    64  		"BIGINT":                           true,
    65  		"BINARY":                           true,
    66  		"BIT":                              true,
    67  		"BIT_LENGTH":                       true,
    68  		"BLOB":                             true,
    69  		"BLOCKED":                          true,
    70  		"BOM":                              true,
    71  		"BOOLEAN":                          true,
    72  		"BOTH":                             true,
    73  		"BREADTH":                          true,
    74  		"BY":                               true,
    75  		"C":                                true,
    76  		"CACHE":                            true,
    77  		"CALL":                             true,
    78  		"CALLED":                           true,
    79  		"CARDINALITY":                      true,
    80  		"CASCADE":                          true,
    81  		"CASCADED":                         true,
    82  		"CASE":                             true,
    83  		"CAST":                             true,
    84  		"CATALOG":                          true,
    85  		"CATALOG_NAME":                     true,
    86  		"CEIL":                             true,
    87  		"CEILING":                          true,
    88  		"CHAIN":                            true,
    89  		"CHAR":                             true,
    90  		"CHARACTER":                        true,
    91  		"CHARACTERISTICS":                  true,
    92  		"CHARACTERS":                       true,
    93  		"CHARACTER_LENGTH":                 true,
    94  		"CHARACTER_SET_CATALOG":            true,
    95  		"CHARACTER_SET_NAME":               true,
    96  		"CHARACTER_SET_SCHEMA":             true,
    97  		"CHAR_LENGTH":                      true,
    98  		"CHECK":                            true,
    99  		"CHECKPOINT":                       true,
   100  		"CLASS":                            true,
   101  		"CLASS_ORIGIN":                     true,
   102  		"CLOB":                             true,
   103  		"CLOSE":                            true,
   104  		"CLUSTER":                          true,
   105  		"COALESCE":                         true,
   106  		"COBOL":                            true,
   107  		"COLLATE":                          true,
   108  		"COLLATION":                        true,
   109  		"COLLATION_CATALOG":                true,
   110  		"COLLATION_NAME":                   true,
   111  		"COLLATION_SCHEMA":                 true,
   112  		"COLLECT":                          true,
   113  		"COLUMN":                           true,
   114  		"COLUMNS":                          true,
   115  		"COLUMN_NAME":                      true,
   116  		"COMMAND_FUNCTION":                 true,
   117  		"COMMAND_FUNCTION_CODE":            true,
   118  		"COMMENT":                          true,
   119  		"COMMENTS":                         true,
   120  		"COMMIT":                           true,
   121  		"COMMITTED":                        true,
   122  		"CONCURRENTLY":                     true,
   123  		"CONDITION":                        true,
   124  		"CONDITION_NUMBER":                 true,
   125  		"CONFIGURATION":                    true,
   126  		"CONNECT":                          true,
   127  		"CONNECTION":                       true,
   128  		"CONNECTION_NAME":                  true,
   129  		"CONSTRAINT":                       true,
   130  		"CONSTRAINTS":                      true,
   131  		"CONSTRAINT_CATALOG":               true,
   132  		"CONSTRAINT_NAME":                  true,
   133  		"CONSTRAINT_SCHEMA":                true,
   134  		"CONSTRUCTOR":                      true,
   135  		"CONTAINS":                         true,
   136  		"CONTENT":                          true,
   137  		"CONTINUE":                         true,
   138  		"CONTROL":                          true,
   139  		"CONVERSION":                       true,
   140  		"CONVERT":                          true,
   141  		"COPY":                             true,
   142  		"CORR":                             true,
   143  		"CORRESPONDING":                    true,
   144  		"COST":                             true,
   145  		"COUNT":                            true,
   146  		"COVAR_POP":                        true,
   147  		"COVAR_SAMP":                       true,
   148  		"CREATE":                           true,
   149  		"CROSS":                            true,
   150  		"CSV":                              true,
   151  		"CUBE":                             true,
   152  		"CUME_DIST":                        true,
   153  		"CURRENT":                          true,
   154  		"CURRENT_CATALOG":                  true,
   155  		"CURRENT_DATE":                     true,
   156  		"CURRENT_DEFAULT_TRANSFORM_GROUP":  true,
   157  		"CURRENT_PATH":                     true,
   158  		"CURRENT_ROLE":                     true,
   159  		"CURRENT_ROW":                      true,
   160  		"CURRENT_SCHEMA":                   true,
   161  		"CURRENT_TIME":                     true,
   162  		"CURRENT_TIMESTAMP":                true,
   163  		"CURRENT_TRANSFORM_GROUP_FOR_TYPE": true,
   164  		"CURRENT_USER":                     true,
   165  		"CURSOR":                           true,
   166  		"CURSOR_NAME":                      true,
   167  		"CYCLE":                            true,
   168  		"DATA":                             true,
   169  		"DATABASE":                         true,
   170  		"DATALINK":                         true,
   171  		"DATE":                             true,
   172  		"DATETIME_INTERVAL_CODE":      true,
   173  		"DATETIME_INTERVAL_PRECISION": true,
   174  		"DAY":                        true,
   175  		"DB":                         true,
   176  		"DEALLOCATE":                 true,
   177  		"DEC":                        true,
   178  		"DECIMAL":                    true,
   179  		"DECLARE":                    true,
   180  		"DEFAULT":                    true,
   181  		"DEFAULTS":                   true,
   182  		"DEFERRABLE":                 true,
   183  		"DEFERRED":                   true,
   184  		"DEFINED":                    true,
   185  		"DEFINER":                    true,
   186  		"DEGREE":                     true,
   187  		"DELETE":                     true,
   188  		"DELIMITER":                  true,
   189  		"DELIMITERS":                 true,
   190  		"DENSE_RANK":                 true,
   191  		"DEPTH":                      true,
   192  		"DEREF":                      true,
   193  		"DERIVED":                    true,
   194  		"DESC":                       true,
   195  		"DESCRIBE":                   true,
   196  		"DESCRIPTOR":                 true,
   197  		"DETERMINISTIC":              true,
   198  		"DIAGNOSTICS":                true,
   199  		"DICTIONARY":                 true,
   200  		"DISABLE":                    true,
   201  		"DISCARD":                    true,
   202  		"DISCONNECT":                 true,
   203  		"DISPATCH":                   true,
   204  		"DISTINCT":                   true,
   205  		"DLNEWCOPY":                  true,
   206  		"DLPREVIOUSCOPY":             true,
   207  		"DLURLCOMPLETE":              true,
   208  		"DLURLCOMPLETEONLY":          true,
   209  		"DLURLCOMPLETEWRITE":         true,
   210  		"DLURLPATH":                  true,
   211  		"DLURLPATHONLY":              true,
   212  		"DLURLPATHWRITE":             true,
   213  		"DLURLSCHEME":                true,
   214  		"DLURLSERVER":                true,
   215  		"DLVALUE":                    true,
   216  		"DO":                         true,
   217  		"DOCUMENT":                   true,
   218  		"DOMAIN":                     true,
   219  		"DOUBLE":                     true,
   220  		"DROP":                       true,
   221  		"DYNAMIC":                    true,
   222  		"DYNAMIC_FUNCTION":           true,
   223  		"DYNAMIC_FUNCTION_CODE":      true,
   224  		"EACH":                       true,
   225  		"ELEMENT":                    true,
   226  		"ELSE":                       true,
   227  		"EMPTY":                      true,
   228  		"ENABLE":                     true,
   229  		"ENCODING":                   true,
   230  		"ENCRYPTED":                  true,
   231  		"END":                        true,
   232  		"END-EXEC":                   true,
   233  		"END_FRAME":                  true,
   234  		"END_PARTITION":              true,
   235  		"ENFORCED":                   true,
   236  		"ENUM":                       true,
   237  		"EQUALS":                     true,
   238  		"ESCAPE":                     true,
   239  		"EVENT":                      true,
   240  		"EVERY":                      true,
   241  		"EXCEPT":                     true,
   242  		"EXCEPTION":                  true,
   243  		"EXCLUDE":                    true,
   244  		"EXCLUDING":                  true,
   245  		"EXCLUSIVE":                  true,
   246  		"EXEC":                       true,
   247  		"EXECUTE":                    true,
   248  		"EXISTS":                     true,
   249  		"EXP":                        true,
   250  		"EXPLAIN":                    true,
   251  		"EXPRESSION":                 true,
   252  		"EXTENSION":                  true,
   253  		"EXTERNAL":                   true,
   254  		"EXTRACT":                    true,
   255  		"FALSE":                      true,
   256  		"FAMILY":                     true,
   257  		"FETCH":                      true,
   258  		"FILE":                       true,
   259  		"FILTER":                     true,
   260  		"FINAL":                      true,
   261  		"FIRST":                      true,
   262  		"FIRST_VALUE":                true,
   263  		"FLAG":                       true,
   264  		"FLOAT":                      true,
   265  		"FLOOR":                      true,
   266  		"FOLLOWING":                  true,
   267  		"FOR":                        true,
   268  		"FORCE":                      true,
   269  		"FOREIGN":                    true,
   270  		"FORTRAN":                    true,
   271  		"FORWARD":                    true,
   272  		"FOUND":                      true,
   273  		"FRAME_ROW":                  true,
   274  		"FREE":                       true,
   275  		"FREEZE":                     true,
   276  		"FROM":                       true,
   277  		"FS":                         true,
   278  		"FULL":                       true,
   279  		"FUNCTION":                   true,
   280  		"FUNCTIONS":                  true,
   281  		"FUSION":                     true,
   282  		"G":                          true,
   283  		"GENERAL":                    true,
   284  		"GENERATED":                  true,
   285  		"GET":                        true,
   286  		"GLOBAL":                     true,
   287  		"GO":                         true,
   288  		"GOTO":                       true,
   289  		"GRANT":                      true,
   290  		"GRANTED":                    true,
   291  		"GREATEST":                   true,
   292  		"GROUP":                      true,
   293  		"GROUPING":                   true,
   294  		"GROUPS":                     true,
   295  		"HANDLER":                    true,
   296  		"HAVING":                     true,
   297  		"HEADER":                     true,
   298  		"HEX":                        true,
   299  		"HIERARCHY":                  true,
   300  		"HOLD":                       true,
   301  		"HOUR":                       true,
   302  		"ID":                         true,
   303  		"IDENTITY":                   true,
   304  		"IF":                         true,
   305  		"IGNORE":                     true,
   306  		"ILIKE":                      true,
   307  		"IMMEDIATE":                  true,
   308  		"IMMEDIATELY":                true,
   309  		"IMMUTABLE":                  true,
   310  		"IMPLEMENTATION":             true,
   311  		"IMPLICIT":                   true,
   312  		"IMPORT":                     true,
   313  		"IN":                         true,
   314  		"INCLUDING":                  true,
   315  		"INCREMENT":                  true,
   316  		"INDENT":                     true,
   317  		"INDEX":                      true,
   318  		"INDEXES":                    true,
   319  		"INDICATOR":                  true,
   320  		"INHERIT":                    true,
   321  		"INHERITS":                   true,
   322  		"INITIALLY":                  true,
   323  		"INLINE":                     true,
   324  		"INNER":                      true,
   325  		"INOUT":                      true,
   326  		"INPUT":                      true,
   327  		"INSENSITIVE":                true,
   328  		"INSERT":                     true,
   329  		"INSTANCE":                   true,
   330  		"INSTANTIABLE":               true,
   331  		"INSTEAD":                    true,
   332  		"INT":                        true,
   333  		"INTEGER":                    true,
   334  		"INTEGRITY":                  true,
   335  		"INTERSECT":                  true,
   336  		"INTERSECTION":               true,
   337  		"INTERVAL":                   true,
   338  		"INTO":                       true,
   339  		"INVOKER":                    true,
   340  		"IS":                         true,
   341  		"ISNULL":                     true,
   342  		"ISOLATION":                  true,
   343  		"JOIN":                       true,
   344  		"K":                          true,
   345  		"KEY":                        true,
   346  		"KEY_MEMBER":                 true,
   347  		"KEY_TYPE":                   true,
   348  		"LABEL":                      true,
   349  		"LAG":                        true,
   350  		"LANGUAGE":                   true,
   351  		"LARGE":                      true,
   352  		"LAST":                       true,
   353  		"LAST_VALUE":                 true,
   354  		"LATERAL":                    true,
   355  		"LC_COLLATE":                 true,
   356  		"LC_CTYPE":                   true,
   357  		"LEAD":                       true,
   358  		"LEADING":                    true,
   359  		"LEAKPROOF":                  true,
   360  		"LEAST":                      true,
   361  		"LEFT":                       true,
   362  		"LENGTH":                     true,
   363  		"LEVEL":                      true,
   364  		"LIBRARY":                    true,
   365  		"LIKE":                       true,
   366  		"LIKE_REGEX":                 true,
   367  		"LIMIT":                      true,
   368  		"LINK":                       true,
   369  		"LISTEN":                     true,
   370  		"LN":                         true,
   371  		"LOAD":                       true,
   372  		"LOCAL":                      true,
   373  		"LOCALTIME":                  true,
   374  		"LOCALTIMESTAMP":             true,
   375  		"LOCATION":                   true,
   376  		"LOCATOR":                    true,
   377  		"LOCK":                       true,
   378  		"LOWER":                      true,
   379  		"M":                          true,
   380  		"MAP":                        true,
   381  		"MAPPING":                    true,
   382  		"MATCH":                      true,
   383  		"MATCHED":                    true,
   384  		"MATERIALIZED":               true,
   385  		"MAX":                        true,
   386  		"MAXVALUE":                   true,
   387  		"MAX_CARDINALITY":            true,
   388  		"MEMBER":                     true,
   389  		"MERGE":                      true,
   390  		"MESSAGE_LENGTH":             true,
   391  		"MESSAGE_OCTET_LENGTH":       true,
   392  		"MESSAGE_TEXT":               true,
   393  		"METHOD":                     true,
   394  		"MIN":                        true,
   395  		"MINUTE":                     true,
   396  		"MINVALUE":                   true,
   397  		"MOD":                        true,
   398  		"MODE":                       true,
   399  		"MODIFIES":                   true,
   400  		"MODULE":                     true,
   401  		"MONTH":                      true,
   402  		"MORE":                       true,
   403  		"MOVE":                       true,
   404  		"MULTISET":                   true,
   405  		"MUMPS":                      true,
   406  		"NAME":                       true,
   407  		"NAMES":                      true,
   408  		"NAMESPACE":                  true,
   409  		"NATIONAL":                   true,
   410  		"NATURAL":                    true,
   411  		"NCHAR":                      true,
   412  		"NCLOB":                      true,
   413  		"NESTING":                    true,
   414  		"NEW":                        true,
   415  		"NEXT":                       true,
   416  		"NFC":                        true,
   417  		"NFD":                        true,
   418  		"NFKC":                       true,
   419  		"NFKD":                       true,
   420  		"NIL":                        true,
   421  		"NO":                         true,
   422  		"NONE":                       true,
   423  		"NORMALIZE":                  true,
   424  		"NORMALIZED":                 true,
   425  		"NOT":                        true,
   426  		"NOTHING":                    true,
   427  		"NOTIFY":                     true,
   428  		"NOTNULL":                    true,
   429  		"NOWAIT":                     true,
   430  		"NTH_VALUE":                  true,
   431  		"NTILE":                      true,
   432  		"NULL":                       true,
   433  		"NULLABLE":                   true,
   434  		"NULLIF":                     true,
   435  		"NULLS":                      true,
   436  		"NUMBER":                     true,
   437  		"NUMERIC":                    true,
   438  		"OBJECT":                     true,
   439  		"OCCURRENCES_REGEX":          true,
   440  		"OCTETS":                     true,
   441  		"OCTET_LENGTH":               true,
   442  		"OF":                         true,
   443  		"OFF":                        true,
   444  		"OFFSET":                     true,
   445  		"OIDS":                       true,
   446  		"OLD":                        true,
   447  		"ON":                         true,
   448  		"ONLY":                       true,
   449  		"OPEN":                       true,
   450  		"OPERATOR":                   true,
   451  		"OPTION":                     true,
   452  		"OPTIONS":                    true,
   453  		"OR":                         true,
   454  		"ORDER":                      true,
   455  		"ORDERING":                   true,
   456  		"ORDINALITY":                 true,
   457  		"OTHERS":                     true,
   458  		"OUT":                        true,
   459  		"OUTER":                      true,
   460  		"OUTPUT":                     true,
   461  		"OVER":                       true,
   462  		"OVERLAPS":                   true,
   463  		"OVERLAY":                    true,
   464  		"OVERRIDING":                 true,
   465  		"OWNED":                      true,
   466  		"OWNER":                      true,
   467  		"P":                          true,
   468  		"PAD":                        true,
   469  		"PARAMETER":                  true,
   470  		"PARAMETER_MODE":             true,
   471  		"PARAMETER_NAME":             true,
   472  		"PARAMETER_ORDINAL_POSITION": true,
   473  		"PARAMETER_SPECIFIC_CATALOG": true,
   474  		"PARAMETER_SPECIFIC_NAME":    true,
   475  		"PARAMETER_SPECIFIC_SCHEMA":  true,
   476  		"PARSER":                     true,
   477  		"PARTIAL":                    true,
   478  		"PARTITION":                  true,
   479  		"PASCAL":                     true,
   480  		"PASSING":                    true,
   481  		"PASSTHROUGH":                true,
   482  		"PASSWORD":                   true,
   483  		"PATH":                       true,
   484  		"PERCENT":                    true,
   485  		"PERCENTILE_CONT":            true,
   486  		"PERCENTILE_DISC":            true,
   487  		"PERCENT_RANK":               true,
   488  		"PERIOD":                     true,
   489  		"PERMISSION":                 true,
   490  		"PLACING":                    true,
   491  		"PLANS":                      true,
   492  		"PLI":                        true,
   493  		"PORTION":                    true,
   494  		"POSITION":                   true,
   495  		"POSITION_REGEX":             true,
   496  		"POWER":                      true,
   497  		"PRECEDES":                   true,
   498  		"PRECEDING":                  true,
   499  		"PRECISION":                  true,
   500  		"PREPARE":                    true,
   501  		"PREPARED":                   true,
   502  		"PRESERVE":                   true,
   503  		"PRIMARY":                    true,
   504  		"PRIOR":                      true,
   505  		"PRIVILEGES":                 true,
   506  		"PROCEDURAL":                 true,
   507  		"PROCEDURE":                  true,
   508  		"PROGRAM":                    true,
   509  		"PUBLIC":                     true,
   510  		"QUOTE":                      true,
   511  		"RANGE":                      true,
   512  		"RANK":                       true,
   513  		"READ":                       true,
   514  		"READS":                      true,
   515  		"REAL":                       true,
   516  		"REASSIGN":                   true,
   517  		"RECHECK":                    true,
   518  		"RECOVERY":                   true,
   519  		"RECURSIVE":                  true,
   520  		"REF":                        true,
   521  		"REFERENCES":                 true,
   522  		"REFERENCING":                true,
   523  		"REFRESH":                    true,
   524  		"REGR_AVGX":                  true,
   525  		"REGR_AVGY":                  true,
   526  		"REGR_COUNT":                 true,
   527  		"REGR_INTERCEPT":             true,
   528  		"REGR_R2":                    true,
   529  		"REGR_SLOPE":                 true,
   530  		"REGR_SXX":                   true,
   531  		"REGR_SXY":                   true,
   532  		"REGR_SYY":                   true,
   533  		"REINDEX":                    true,
   534  		"RELATIVE":                   true,
   535  		"RELEASE":                    true,
   536  		"RENAME":                     true,
   537  		"REPEATABLE":                 true,
   538  		"REPLACE":                    true,
   539  		"REPLICA":                    true,
   540  		"REQUIRING":                  true,
   541  		"RESET":                      true,
   542  		"RESPECT":                    true,
   543  		"RESTART":                    true,
   544  		"RESTORE":                    true,
   545  		"RESTRICT":                   true,
   546  		"RESULT":                     true,
   547  		"RETURN":                     true,
   548  		"RETURNED_CARDINALITY":       true,
   549  		"RETURNED_LENGTH":            true,
   550  		"RETURNED_OCTET_LENGTH":      true,
   551  		"RETURNED_SQLSTATE":          true,
   552  		"RETURNING":                  true,
   553  		"RETURNS":                    true,
   554  		"REVOKE":                     true,
   555  		"RIGHT":                      true,
   556  		"ROLE":                       true,
   557  		"ROLLBACK":                   true,
   558  		"ROLLUP":                     true,
   559  		"ROUTINE":                    true,
   560  		"ROUTINE_CATALOG":            true,
   561  		"ROUTINE_NAME":               true,
   562  		"ROUTINE_SCHEMA":             true,
   563  		"ROW":                        true,
   564  		"ROWS":                       true,
   565  		"ROW_COUNT":                  true,
   566  		"ROW_NUMBER":                 true,
   567  		"RULE":                       true,
   568  		"SAVEPOINT":                  true,
   569  		"SCALE":                      true,
   570  		"SCHEMA":                     true,
   571  		"SCHEMA_NAME":                true,
   572  		"SCOPE":                      true,
   573  		"SCOPE_CATALOG":              true,
   574  		"SCOPE_NAME":                 true,
   575  		"SCOPE_SCHEMA":               true,
   576  		"SCROLL":                     true,
   577  		"SEARCH":                     true,
   578  		"SECOND":                     true,
   579  		"SECTION":                    true,
   580  		"SECURITY":                   true,
   581  		"SELECT":                     true,
   582  		"SELECTIVE":                  true,
   583  		"SELF":                       true,
   584  		"SENSITIVE":                  true,
   585  		"SEQUENCE":                   true,
   586  		"SEQUENCES":                  true,
   587  		"SERIALIZABLE":               true,
   588  		"SERVER":                     true,
   589  		"SERVER_NAME":                true,
   590  		"SESSION":                    true,
   591  		"SESSION_USER":               true,
   592  		"SET":                        true,
   593  		"SETOF":                      true,
   594  		"SETS":                       true,
   595  		"SHARE":                      true,
   596  		"SHOW":                       true,
   597  		"SIMILAR":                    true,
   598  		"SIMPLE":                     true,
   599  		"SIZE":                       true,
   600  		"SMALLINT":                   true,
   601  		"SNAPSHOT":                   true,
   602  		"SOME":                       true,
   603  		"SOURCE":                     true,
   604  		"SPACE":                      true,
   605  		"SPECIFIC":                   true,
   606  		"SPECIFICTYPE":               true,
   607  		"SPECIFIC_NAME":              true,
   608  		"SQL":                        true,
   609  		"SQLCODE":                    true,
   610  		"SQLERROR":                   true,
   611  		"SQLEXCEPTION":               true,
   612  		"SQLSTATE":                   true,
   613  		"SQLWARNING":                 true,
   614  		"SQRT":                       true,
   615  		"STABLE":                     true,
   616  		"STANDALONE":                 true,
   617  		"START":                      true,
   618  		"STATE":                      true,
   619  		"STATEMENT":                  true,
   620  		"STATIC":                     true,
   621  		"STATISTICS":                 true,
   622  		"STDDEV_POP":                 true,
   623  		"STDDEV_SAMP":                true,
   624  		"STDIN":                      true,
   625  		"STDOUT":                     true,
   626  		"STORAGE":                    true,
   627  		"STRICT":                     true,
   628  		"STRIP":                      true,
   629  		"STRUCTURE":                  true,
   630  		"STYLE":                      true,
   631  		"SUBCLASS_ORIGIN":            true,
   632  		"SUBMULTISET":                true,
   633  		"SUBSTRING":                  true,
   634  		"SUBSTRING_REGEX":            true,
   635  		"SUCCEEDS":                   true,
   636  		"SUM":                        true,
   637  		"SYMMETRIC":                  true,
   638  		"SYSID":                      true,
   639  		"SYSTEM":                     true,
   640  		"SYSTEM_TIME":                true,
   641  		"SYSTEM_USER":                true,
   642  		"T":                          true,
   643  		"TABLE":                      true,
   644  		"TABLES":                     true,
   645  		"TABLESAMPLE":                true,
   646  		"TABLESPACE":                 true,
   647  		"TABLE_NAME":                 true,
   648  		"TEMP":                       true,
   649  		"TEMPLATE":                   true,
   650  		"TEMPORARY":                  true,
   651  		"TEXT":                       true,
   652  		"THEN":                       true,
   653  		"TIES":                       true,
   654  		"TIME":                       true,
   655  		"TIMESTAMP":                  true,
   656  		"TIMEZONE_HOUR":              true,
   657  		"TIMEZONE_MINUTE":            true,
   658  		"TO":                         true,
   659  		"TOKEN":                      true,
   660  		"TOP_LEVEL_COUNT":            true,
   661  		"TRAILING":                   true,
   662  		"TRANSACTION":                true,
   663  		"TRANSACTIONS_COMMITTED":     true,
   664  		"TRANSACTIONS_ROLLED_BACK":   true,
   665  		"TRANSACTION_ACTIVE":         true,
   666  		"TRANSFORM":                  true,
   667  		"TRANSFORMS":                 true,
   668  		"TRANSLATE":                  true,
   669  		"TRANSLATE_REGEX":            true,
   670  		"TRANSLATION":                true,
   671  		"TREAT":                      true,
   672  		"TRIGGER":                    true,
   673  		"TRIGGER_CATALOG":            true,
   674  		"TRIGGER_NAME":               true,
   675  		"TRIGGER_SCHEMA":             true,
   676  		"TRIM":                       true,
   677  		"TRIM_ARRAY":                 true,
   678  		"TRUE":                       true,
   679  		"TRUNCATE":                   true,
   680  		"TRUSTED":                    true,
   681  		"TYPE":                       true,
   682  		"TYPES":                      true,
   683  		"UESCAPE":                    true,
   684  		"UNBOUNDED":                  true,
   685  		"UNCOMMITTED":                true,
   686  		"UNDER":                      true,
   687  		"UNENCRYPTED":                true,
   688  		"UNION":                      true,
   689  		"UNIQUE":                     true,
   690  		"UNKNOWN":                    true,
   691  		"UNLINK":                     true,
   692  		"UNLISTEN":                   true,
   693  		"UNLOGGED":                   true,
   694  		"UNNAMED":                    true,
   695  		"UNNEST":                     true,
   696  		"UNTIL":                      true,
   697  		"UNTYPED":                    true,
   698  		"UPDATE":                     true,
   699  		"UPPER":                      true,
   700  		"URI":                        true,
   701  		"USAGE":                      true,
   702  		"USER":                       true,
   703  		"USER_DEFINED_TYPE_CATALOG": true,
   704  		"USER_DEFINED_TYPE_CODE":    true,
   705  		"USER_DEFINED_TYPE_NAME":    true,
   706  		"USER_DEFINED_TYPE_SCHEMA":  true,
   707  		"USING":                     true,
   708  		"VACUUM":                    true,
   709  		"VALID":                     true,
   710  		"VALIDATE":                  true,
   711  		"VALIDATOR":                 true,
   712  		"VALUE":                     true,
   713  		"VALUES":                    true,
   714  		"VALUE_OF":                  true,
   715  		"VARBINARY":                 true,
   716  		"VARCHAR":                   true,
   717  		"VARIADIC":                  true,
   718  		"VARYING":                   true,
   719  		"VAR_POP":                   true,
   720  		"VAR_SAMP":                  true,
   721  		"VERBOSE":                   true,
   722  		"VERSION":                   true,
   723  		"VERSIONING":                true,
   724  		"VIEW":                      true,
   725  		"VOLATILE":                  true,
   726  		"WHEN":                      true,
   727  		"WHENEVER":                  true,
   728  		"WHERE":                     true,
   729  		"WHITESPACE":                true,
   730  		"WIDTH_BUCKET":              true,
   731  		"WINDOW":                    true,
   732  		"WITH":                      true,
   733  		"WITHIN":                    true,
   734  		"WITHOUT":                   true,
   735  		"WORK":                      true,
   736  		"WRAPPER":                   true,
   737  		"WRITE":                     true,
   738  		"XML":                       true,
   739  		"XMLAGG":                    true,
   740  		"XMLATTRIBUTES":             true,
   741  		"XMLBINARY":                 true,
   742  		"XMLCAST":                   true,
   743  		"XMLCOMMENT":                true,
   744  		"XMLCONCAT":                 true,
   745  		"XMLDECLARATION":            true,
   746  		"XMLDOCUMENT":               true,
   747  		"XMLELEMENT":                true,
   748  		"XMLEXISTS":                 true,
   749  		"XMLFOREST":                 true,
   750  		"XMLITERATE":                true,
   751  		"XMLNAMESPACES":             true,
   752  		"XMLPARSE":                  true,
   753  		"XMLPI":                     true,
   754  		"XMLQUERY":                  true,
   755  		"XMLROOT":                   true,
   756  		"XMLSCHEMA":                 true,
   757  		"XMLSERIALIZE":              true,
   758  		"XMLTABLE":                  true,
   759  		"XMLTEXT":                   true,
   760  		"XMLVALIDATE":               true,
   761  		"YEAR":                      true,
   762  		"YES":                       true,
   763  		"ZONE":                      true,
   764  	}
   765  )
   766  
   767  type postgres struct {
   768  	core.Base
   769  }
   770  
   771  func (db *postgres) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error {
   772  	return db.Base.Init(d, db, uri, drivername, dataSourceName)
   773  }
   774  
   775  func (db *postgres) SqlType(c *core.Column) string {
   776  	var res string
   777  	switch t := c.SQLType.Name; t {
   778  	case core.TinyInt:
   779  		res = core.SmallInt
   780  		return res
   781  	case core.MediumInt, core.Int, core.Integer:
   782  		if c.IsAutoIncrement {
   783  			return core.Serial
   784  		}
   785  		return core.Integer
   786  	case core.Serial, core.BigSerial:
   787  		c.IsAutoIncrement = true
   788  		c.Nullable = false
   789  		res = t
   790  	case core.Binary, core.VarBinary:
   791  		return core.Bytea
   792  	case core.DateTime:
   793  		res = core.TimeStamp
   794  	case core.TimeStampz:
   795  		return "timestamp with time zone"
   796  	case core.Float:
   797  		res = core.Real
   798  	case core.TinyText, core.MediumText, core.LongText:
   799  		res = core.Text
   800  	case core.NVarchar:
   801  		res = core.Varchar
   802  	case core.Uuid:
   803  		res = core.Uuid
   804  	case core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob:
   805  		return core.Bytea
   806  	case core.Double:
   807  		return "DOUBLE PRECISION"
   808  	default:
   809  		if c.IsAutoIncrement {
   810  			return core.Serial
   811  		}
   812  		res = t
   813  	}
   814  
   815  	hasLen1 := (c.Length > 0)
   816  	hasLen2 := (c.Length2 > 0)
   817  
   818  	if hasLen2 {
   819  		res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
   820  	} else if hasLen1 {
   821  		res += "(" + strconv.Itoa(c.Length) + ")"
   822  	}
   823  	return res
   824  }
   825  
   826  func (db *postgres) SupportInsertMany() bool {
   827  	return true
   828  }
   829  
   830  func (db *postgres) IsReserved(name string) bool {
   831  	_, ok := postgresReservedWords[name]
   832  	return ok
   833  }
   834  
   835  func (db *postgres) Quote(name string) string {
   836  	name = strings.Replace(name, ".", `"."`, -1)
   837  	return "\"" + name + "\""
   838  }
   839  
   840  func (db *postgres) QuoteStr() string {
   841  	return "\""
   842  }
   843  
   844  func (db *postgres) AutoIncrStr() string {
   845  	return ""
   846  }
   847  
   848  func (db *postgres) SupportEngine() bool {
   849  	return false
   850  }
   851  
   852  func (db *postgres) SupportCharset() bool {
   853  	return false
   854  }
   855  
   856  func (db *postgres) IndexOnTable() bool {
   857  	return false
   858  }
   859  
   860  func (db *postgres) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
   861  	args := []interface{}{tableName, idxName}
   862  	return `SELECT indexname FROM pg_indexes ` +
   863  		`WHERE tablename = ? AND indexname = ?`, args
   864  }
   865  
   866  func (db *postgres) TableCheckSql(tableName string) (string, []interface{}) {
   867  	args := []interface{}{tableName}
   868  	return `SELECT tablename FROM pg_tables WHERE tablename = ?`, args
   869  }
   870  
   871  /*func (db *postgres) ColumnCheckSql(tableName, colName string) (string, []interface{}) {
   872  	args := []interface{}{tableName, colName}
   873  	return "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ?" +
   874  		" AND column_name = ?", args
   875  }*/
   876  
   877  func (db *postgres) ModifyColumnSql(tableName string, col *core.Column) string {
   878  	return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s",
   879  		tableName, col.Name, db.SqlType(col))
   880  }
   881  
   882  func (db *postgres) DropIndexSql(tableName string, index *core.Index) string {
   883  	//var unique string
   884  	quote := db.Quote
   885  	idxName := index.Name
   886  
   887  	if !strings.HasPrefix(idxName, "UQE_") &&
   888  		!strings.HasPrefix(idxName, "IDX_") {
   889  		if index.Type == core.UniqueType {
   890  			idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
   891  		} else {
   892  			idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
   893  		}
   894  	}
   895  	return fmt.Sprintf("DROP INDEX %v", quote(idxName))
   896  }
   897  
   898  func (db *postgres) IsColumnExist(tableName, colName string) (bool, error) {
   899  	args := []interface{}{tableName, colName}
   900  	query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" +
   901  		" AND column_name = $2"
   902  	db.LogSQL(query, args)
   903  
   904  	rows, err := db.DB().Query(query, args...)
   905  	if err != nil {
   906  		return false, err
   907  	}
   908  	defer rows.Close()
   909  
   910  	return rows.Next(), nil
   911  }
   912  
   913  func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
   914  	// FIXME: the schema should be replaced by user custom's
   915  	args := []interface{}{tableName, "public"}
   916  	s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix ,
   917      CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
   918      CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey
   919  FROM pg_attribute f
   920      JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid
   921      LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
   922      LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
   923      LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
   924      LEFT JOIN pg_class AS g ON p.confrelid = g.oid
   925      LEFT JOIN INFORMATION_SCHEMA.COLUMNS s ON s.column_name=f.attname AND c.relname=s.table_name
   926  WHERE c.relkind = 'r'::char AND c.relname = $1 AND s.table_schema = $2 AND f.attnum > 0 ORDER BY f.attnum;`
   927  	db.LogSQL(s, args)
   928  
   929  	rows, err := db.DB().Query(s, args...)
   930  	if err != nil {
   931  		return nil, nil, err
   932  	}
   933  	defer rows.Close()
   934  
   935  	cols := make(map[string]*core.Column)
   936  	colSeq := make([]string, 0)
   937  
   938  	for rows.Next() {
   939  		col := new(core.Column)
   940  		col.Indexes = make(map[string]int)
   941  
   942  		var colName, isNullable, dataType string
   943  		var maxLenStr, colDefault, numPrecision, numRadix *string
   944  		var isPK, isUnique bool
   945  		err = rows.Scan(&colName, &colDefault, &isNullable, &dataType, &maxLenStr, &numPrecision, &numRadix, &isPK, &isUnique)
   946  		if err != nil {
   947  			return nil, nil, err
   948  		}
   949  
   950  		//fmt.Println(args, colName, isNullable, dataType, maxLenStr, colDefault, numPrecision, numRadix, isPK, isUnique)
   951  		var maxLen int
   952  		if maxLenStr != nil {
   953  			maxLen, err = strconv.Atoi(*maxLenStr)
   954  			if err != nil {
   955  				return nil, nil, err
   956  			}
   957  		}
   958  
   959  		col.Name = strings.Trim(colName, `" `)
   960  
   961  		if colDefault != nil || isPK {
   962  			if isPK {
   963  				col.IsPrimaryKey = true
   964  			} else {
   965  				col.Default = *colDefault
   966  			}
   967  		}
   968  
   969  		if colDefault != nil && strings.HasPrefix(*colDefault, "nextval(") {
   970  			col.IsAutoIncrement = true
   971  		}
   972  
   973  		col.Nullable = (isNullable == "YES")
   974  
   975  		switch dataType {
   976  		case "character varying", "character":
   977  			col.SQLType = core.SQLType{Name: core.Varchar, DefaultLength: 0, DefaultLength2: 0}
   978  		case "timestamp without time zone":
   979  			col.SQLType = core.SQLType{Name: core.DateTime, DefaultLength: 0, DefaultLength2: 0}
   980  		case "timestamp with time zone":
   981  			col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
   982  		case "double precision":
   983  			col.SQLType = core.SQLType{Name: core.Double, DefaultLength: 0, DefaultLength2: 0}
   984  		case "boolean":
   985  			col.SQLType = core.SQLType{Name: core.Bool, DefaultLength: 0, DefaultLength2: 0}
   986  		case "time without time zone":
   987  			col.SQLType = core.SQLType{Name: core.Time, DefaultLength: 0, DefaultLength2: 0}
   988  		case "oid":
   989  			col.SQLType = core.SQLType{Name: core.BigInt, DefaultLength: 0, DefaultLength2: 0}
   990  		default:
   991  			col.SQLType = core.SQLType{Name: strings.ToUpper(dataType), DefaultLength: 0, DefaultLength2: 0}
   992  		}
   993  		if _, ok := core.SqlTypes[col.SQLType.Name]; !ok {
   994  			return nil, nil, fmt.Errorf("Unknown colType: %v", dataType)
   995  		}
   996  
   997  		col.Length = maxLen
   998  
   999  		if col.SQLType.IsText() || col.SQLType.IsTime() {
  1000  			if col.Default != "" {
  1001  				col.Default = "'" + col.Default + "'"
  1002  			} else {
  1003  				if col.DefaultIsEmpty {
  1004  					col.Default = "''"
  1005  				}
  1006  			}
  1007  		}
  1008  		cols[col.Name] = col
  1009  		colSeq = append(colSeq, col.Name)
  1010  	}
  1011  
  1012  	return colSeq, cols, nil
  1013  }
  1014  
  1015  func (db *postgres) GetTables() ([]*core.Table, error) {
  1016  	// FIXME: replace public to user customrize schema
  1017  	args := []interface{}{"public"}
  1018  	s := fmt.Sprintf("SELECT tablename FROM pg_tables WHERE schemaname = $1")
  1019  	db.LogSQL(s, args)
  1020  
  1021  	rows, err := db.DB().Query(s, args...)
  1022  	if err != nil {
  1023  		return nil, err
  1024  	}
  1025  	defer rows.Close()
  1026  
  1027  	tables := make([]*core.Table, 0)
  1028  	for rows.Next() {
  1029  		table := core.NewEmptyTable()
  1030  		var name string
  1031  		err = rows.Scan(&name)
  1032  		if err != nil {
  1033  			return nil, err
  1034  		}
  1035  		table.Name = name
  1036  		tables = append(tables, table)
  1037  	}
  1038  	return tables, nil
  1039  }
  1040  
  1041  func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) {
  1042  	// FIXME: replace the public schema to user specify schema
  1043  	args := []interface{}{"public", tableName}
  1044  	s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE schemaname=$1 AND tablename=$2")
  1045  	db.LogSQL(s, args)
  1046  
  1047  	rows, err := db.DB().Query(s, args...)
  1048  	if err != nil {
  1049  		return nil, err
  1050  	}
  1051  	defer rows.Close()
  1052  
  1053  	indexes := make(map[string]*core.Index, 0)
  1054  	for rows.Next() {
  1055  		var indexType int
  1056  		var indexName, indexdef string
  1057  		var colNames []string
  1058  		err = rows.Scan(&indexName, &indexdef)
  1059  		if err != nil {
  1060  			return nil, err
  1061  		}
  1062  		indexName = strings.Trim(indexName, `" `)
  1063  		if strings.HasSuffix(indexName, "_pkey") {
  1064  			continue
  1065  		}
  1066  		if strings.HasPrefix(indexdef, "CREATE UNIQUE INDEX") {
  1067  			indexType = core.UniqueType
  1068  		} else {
  1069  			indexType = core.IndexType
  1070  		}
  1071  		cs := strings.Split(indexdef, "(")
  1072  		colNames = strings.Split(cs[1][0:len(cs[1])-1], ",")
  1073  
  1074  		if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  1075  			newIdxName := indexName[5+len(tableName) : len(indexName)]
  1076  			if newIdxName != "" {
  1077  				indexName = newIdxName
  1078  			}
  1079  		}
  1080  
  1081  		index := &core.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)}
  1082  		for _, colName := range colNames {
  1083  			index.Cols = append(index.Cols, strings.Trim(colName, `" `))
  1084  		}
  1085  		indexes[index.Name] = index
  1086  	}
  1087  	return indexes, nil
  1088  }
  1089  
  1090  func (db *postgres) Filters() []core.Filter {
  1091  	return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}, &core.SeqFilter{Prefix: "$", Start: 1}}
  1092  }