dialect_postgres.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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/go-xorm/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. res = 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. hasLen1 := (c.Length > 0)
  828. hasLen2 := (c.Length2 > 0)
  829. if hasLen2 {
  830. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  831. } else if hasLen1 {
  832. res += "(" + strconv.Itoa(c.Length) + ")"
  833. }
  834. return res
  835. }
  836. func (db *postgres) SupportInsertMany() bool {
  837. return true
  838. }
  839. func (db *postgres) IsReserved(name string) bool {
  840. _, ok := postgresReservedWords[name]
  841. return ok
  842. }
  843. func (db *postgres) Quote(name string) string {
  844. name = strings.Replace(name, ".", `"."`, -1)
  845. return "\"" + name + "\""
  846. }
  847. func (db *postgres) QuoteStr() string {
  848. return "\""
  849. }
  850. func (db *postgres) AutoIncrStr() string {
  851. return ""
  852. }
  853. func (db *postgres) SupportEngine() bool {
  854. return false
  855. }
  856. func (db *postgres) SupportCharset() bool {
  857. return false
  858. }
  859. func (db *postgres) IndexOnTable() bool {
  860. return false
  861. }
  862. func (db *postgres) IndexCheckSql(tableName, idxName string) (string, []interface{}) {
  863. if len(db.Schema) == 0 {
  864. args := []interface{}{tableName, idxName}
  865. return `SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?`, args
  866. }
  867. args := []interface{}{db.Schema, tableName, idxName}
  868. return `SELECT indexname FROM pg_indexes ` +
  869. `WHERE schemaname = ? AND tablename = ? AND indexname = ?`, args
  870. }
  871. func (db *postgres) TableCheckSql(tableName string) (string, []interface{}) {
  872. if len(db.Schema) == 0 {
  873. args := []interface{}{tableName}
  874. return `SELECT tablename FROM pg_tables WHERE tablename = ?`, args
  875. }
  876. args := []interface{}{db.Schema, tableName}
  877. return `SELECT tablename FROM pg_tables WHERE schemaname = ? AND tablename = ?`, args
  878. }
  879. func (db *postgres) ModifyColumnSql(tableName string, col *core.Column) string {
  880. if len(db.Schema) == 0 {
  881. return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s",
  882. tableName, col.Name, db.SqlType(col))
  883. }
  884. return fmt.Sprintf("alter table %s.%s ALTER COLUMN %s TYPE %s",
  885. db.Schema, tableName, col.Name, db.SqlType(col))
  886. }
  887. func (db *postgres) DropIndexSql(tableName string, index *core.Index) string {
  888. quote := db.Quote
  889. idxName := index.Name
  890. tableName = strings.Replace(tableName, `"`, "", -1)
  891. tableName = strings.Replace(tableName, `.`, "_", -1)
  892. if !strings.HasPrefix(idxName, "UQE_") &&
  893. !strings.HasPrefix(idxName, "IDX_") {
  894. if index.Type == core.UniqueType {
  895. idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  896. } else {
  897. idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  898. }
  899. }
  900. if db.Uri.Schema != "" {
  901. idxName = db.Uri.Schema + "." + idxName
  902. }
  903. return fmt.Sprintf("DROP INDEX %v", quote(idxName))
  904. }
  905. func (db *postgres) IsColumnExist(tableName, colName string) (bool, error) {
  906. args := []interface{}{db.Schema, tableName, colName}
  907. query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = $1 AND table_name = $2" +
  908. " AND column_name = $3"
  909. if len(db.Schema) == 0 {
  910. args = []interface{}{tableName, colName}
  911. query = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" +
  912. " AND column_name = $2"
  913. }
  914. db.LogSQL(query, args)
  915. rows, err := db.DB().Query(query, args...)
  916. if err != nil {
  917. return false, err
  918. }
  919. defer rows.Close()
  920. return rows.Next(), nil
  921. }
  922. func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) {
  923. args := []interface{}{tableName}
  924. s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix ,
  925. CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
  926. CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey
  927. FROM pg_attribute f
  928. JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid
  929. LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
  930. LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
  931. LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
  932. LEFT JOIN pg_class AS g ON p.confrelid = g.oid
  933. LEFT JOIN INFORMATION_SCHEMA.COLUMNS s ON s.column_name=f.attname AND c.relname=s.table_name
  934. WHERE c.relkind = 'r'::char AND c.relname = $1%s AND f.attnum > 0 ORDER BY f.attnum;`
  935. var f string
  936. if len(db.Schema) != 0 {
  937. args = append(args, db.Schema)
  938. f = " AND s.table_schema = $2"
  939. }
  940. s = fmt.Sprintf(s, f)
  941. db.LogSQL(s, args)
  942. rows, err := db.DB().Query(s, args...)
  943. if err != nil {
  944. return nil, nil, err
  945. }
  946. defer rows.Close()
  947. cols := make(map[string]*core.Column)
  948. colSeq := make([]string, 0)
  949. for rows.Next() {
  950. col := new(core.Column)
  951. col.Indexes = make(map[string]int)
  952. var colName, isNullable, dataType string
  953. var maxLenStr, colDefault, numPrecision, numRadix *string
  954. var isPK, isUnique bool
  955. err = rows.Scan(&colName, &colDefault, &isNullable, &dataType, &maxLenStr, &numPrecision, &numRadix, &isPK, &isUnique)
  956. if err != nil {
  957. return nil, nil, err
  958. }
  959. //fmt.Println(args, colName, isNullable, dataType, maxLenStr, colDefault, numPrecision, numRadix, isPK, isUnique)
  960. var maxLen int
  961. if maxLenStr != nil {
  962. maxLen, err = strconv.Atoi(*maxLenStr)
  963. if err != nil {
  964. return nil, nil, err
  965. }
  966. }
  967. col.Name = strings.Trim(colName, `" `)
  968. if colDefault != nil || isPK {
  969. if isPK {
  970. col.IsPrimaryKey = true
  971. } else {
  972. col.Default = *colDefault
  973. }
  974. }
  975. if colDefault != nil && strings.HasPrefix(*colDefault, "nextval(") {
  976. col.IsAutoIncrement = true
  977. }
  978. col.Nullable = (isNullable == "YES")
  979. switch dataType {
  980. case "character varying", "character":
  981. col.SQLType = core.SQLType{Name: core.Varchar, DefaultLength: 0, DefaultLength2: 0}
  982. case "timestamp without time zone":
  983. col.SQLType = core.SQLType{Name: core.DateTime, DefaultLength: 0, DefaultLength2: 0}
  984. case "timestamp with time zone":
  985. col.SQLType = core.SQLType{Name: core.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  986. case "double precision":
  987. col.SQLType = core.SQLType{Name: core.Double, DefaultLength: 0, DefaultLength2: 0}
  988. case "boolean":
  989. col.SQLType = core.SQLType{Name: core.Bool, DefaultLength: 0, DefaultLength2: 0}
  990. case "time without time zone":
  991. col.SQLType = core.SQLType{Name: core.Time, DefaultLength: 0, DefaultLength2: 0}
  992. case "oid":
  993. col.SQLType = core.SQLType{Name: core.BigInt, DefaultLength: 0, DefaultLength2: 0}
  994. default:
  995. col.SQLType = core.SQLType{Name: strings.ToUpper(dataType), DefaultLength: 0, DefaultLength2: 0}
  996. }
  997. if _, ok := core.SqlTypes[col.SQLType.Name]; !ok {
  998. return nil, nil, fmt.Errorf("Unknown colType: %v", dataType)
  999. }
  1000. col.Length = maxLen
  1001. if col.SQLType.IsText() || col.SQLType.IsTime() {
  1002. if col.Default != "" {
  1003. col.Default = "'" + col.Default + "'"
  1004. } else {
  1005. if col.DefaultIsEmpty {
  1006. col.Default = "''"
  1007. }
  1008. }
  1009. }
  1010. cols[col.Name] = col
  1011. colSeq = append(colSeq, col.Name)
  1012. }
  1013. return colSeq, cols, nil
  1014. }
  1015. func (db *postgres) GetTables() ([]*core.Table, error) {
  1016. args := []interface{}{}
  1017. s := "SELECT tablename FROM pg_tables"
  1018. if len(db.Schema) != 0 {
  1019. args = append(args, db.Schema)
  1020. s = s + " WHERE schemaname = $1"
  1021. }
  1022. db.LogSQL(s, args)
  1023. rows, err := db.DB().Query(s, args...)
  1024. if err != nil {
  1025. return nil, err
  1026. }
  1027. defer rows.Close()
  1028. tables := make([]*core.Table, 0)
  1029. for rows.Next() {
  1030. table := core.NewEmptyTable()
  1031. var name string
  1032. err = rows.Scan(&name)
  1033. if err != nil {
  1034. return nil, err
  1035. }
  1036. table.Name = name
  1037. tables = append(tables, table)
  1038. }
  1039. return tables, nil
  1040. }
  1041. func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) {
  1042. args := []interface{}{tableName}
  1043. s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE tablename=$1")
  1044. if len(db.Schema) != 0 {
  1045. args = append(args, db.Schema)
  1046. s = s + " AND schemaname=$2"
  1047. }
  1048. db.LogSQL(s, args)
  1049. rows, err := db.DB().Query(s, args...)
  1050. if err != nil {
  1051. return nil, err
  1052. }
  1053. defer rows.Close()
  1054. indexes := make(map[string]*core.Index, 0)
  1055. for rows.Next() {
  1056. var indexType int
  1057. var indexName, indexdef string
  1058. var colNames []string
  1059. err = rows.Scan(&indexName, &indexdef)
  1060. if err != nil {
  1061. return nil, err
  1062. }
  1063. indexName = strings.Trim(indexName, `" `)
  1064. if strings.HasSuffix(indexName, "_pkey") {
  1065. continue
  1066. }
  1067. if strings.HasPrefix(indexdef, "CREATE UNIQUE INDEX") {
  1068. indexType = core.UniqueType
  1069. } else {
  1070. indexType = core.IndexType
  1071. }
  1072. cs := strings.Split(indexdef, "(")
  1073. colNames = strings.Split(cs[1][0:len(cs[1])-1], ",")
  1074. var isRegular bool
  1075. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  1076. newIdxName := indexName[5+len(tableName):]
  1077. isRegular = true
  1078. if newIdxName != "" {
  1079. indexName = newIdxName
  1080. }
  1081. }
  1082. index := &core.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)}
  1083. for _, colName := range colNames {
  1084. index.Cols = append(index.Cols, strings.Trim(colName, `" `))
  1085. }
  1086. index.IsRegular = isRegular
  1087. indexes[index.Name] = index
  1088. }
  1089. return indexes, nil
  1090. }
  1091. func (db *postgres) Filters() []core.Filter {
  1092. return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}, &core.SeqFilter{Prefix: "$", Start: 1}}
  1093. }
  1094. type pqDriver struct {
  1095. }
  1096. type values map[string]string
  1097. func (vs values) Set(k, v string) {
  1098. vs[k] = v
  1099. }
  1100. func (vs values) Get(k string) (v string) {
  1101. return vs[k]
  1102. }
  1103. func parseURL(connstr string) (string, error) {
  1104. u, err := url.Parse(connstr)
  1105. if err != nil {
  1106. return "", err
  1107. }
  1108. if u.Scheme != "postgresql" && u.Scheme != "postgres" {
  1109. return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
  1110. }
  1111. escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
  1112. if u.Path != "" {
  1113. return escaper.Replace(u.Path[1:]), nil
  1114. }
  1115. return "", nil
  1116. }
  1117. func parseOpts(name string, o values) error {
  1118. if len(name) == 0 {
  1119. return fmt.Errorf("invalid options: %s", name)
  1120. }
  1121. name = strings.TrimSpace(name)
  1122. ps := strings.Split(name, " ")
  1123. for _, p := range ps {
  1124. kv := strings.Split(p, "=")
  1125. if len(kv) < 2 {
  1126. return fmt.Errorf("invalid option: %q", p)
  1127. }
  1128. o.Set(kv[0], kv[1])
  1129. }
  1130. return nil
  1131. }
  1132. func (p *pqDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) {
  1133. db := &core.Uri{DbType: core.POSTGRES}
  1134. var err error
  1135. if strings.HasPrefix(dataSourceName, "postgresql://") || strings.HasPrefix(dataSourceName, "postgres://") {
  1136. db.DbName, err = parseURL(dataSourceName)
  1137. if err != nil {
  1138. return nil, err
  1139. }
  1140. } else {
  1141. o := make(values)
  1142. err = parseOpts(dataSourceName, o)
  1143. if err != nil {
  1144. return nil, err
  1145. }
  1146. db.DbName = o.Get("dbname")
  1147. }
  1148. if db.DbName == "" {
  1149. return nil, errors.New("dbname is empty")
  1150. }
  1151. return db, nil
  1152. }
  1153. type pqDriverPgx struct {
  1154. pqDriver
  1155. }
  1156. func (pgx *pqDriverPgx) Parse(driverName, dataSourceName string) (*core.Uri, error) {
  1157. // Remove the leading characters for driver to work
  1158. if len(dataSourceName) >= 9 && dataSourceName[0] == 0 {
  1159. dataSourceName = dataSourceName[9:]
  1160. }
  1161. return pgx.pqDriver.Parse(driverName, dataSourceName)
  1162. }