dialect_postgres.go 45 KB

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