You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

postgres.go 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  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 dialects
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "xorm.io/xorm/core"
  13. "xorm.io/xorm/schemas"
  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. postgresQuoter = schemas.Quoter{'"', '"', schemas.AlwaysReserve}
  766. )
  767. var (
  768. // DefaultPostgresSchema default postgres schema
  769. DefaultPostgresSchema = "public"
  770. )
  771. type postgres struct {
  772. Base
  773. }
  774. func (db *postgres) Init(uri *URI) error {
  775. db.quoter = postgresQuoter
  776. return db.Base.Init(db, uri)
  777. }
  778. func (db *postgres) getSchema() string {
  779. if db.uri.Schema != "" {
  780. return db.uri.Schema
  781. }
  782. return DefaultPostgresSchema
  783. }
  784. func (db *postgres) needQuote(name string) bool {
  785. if db.IsReserved(name) {
  786. return true
  787. }
  788. for _, c := range name {
  789. if c >= 'A' && c <= 'Z' {
  790. return true
  791. }
  792. }
  793. return false
  794. }
  795. func (db *postgres) SetQuotePolicy(quotePolicy QuotePolicy) {
  796. switch quotePolicy {
  797. case QuotePolicyNone:
  798. var q = postgresQuoter
  799. q.IsReserved = schemas.AlwaysNoReserve
  800. db.quoter = q
  801. case QuotePolicyReserved:
  802. var q = postgresQuoter
  803. q.IsReserved = db.needQuote
  804. db.quoter = q
  805. case QuotePolicyAlways:
  806. fallthrough
  807. default:
  808. db.quoter = postgresQuoter
  809. }
  810. }
  811. func (db *postgres) SQLType(c *schemas.Column) string {
  812. var res string
  813. switch t := c.SQLType.Name; t {
  814. case schemas.TinyInt:
  815. res = schemas.SmallInt
  816. return res
  817. case schemas.Bit:
  818. res = schemas.Boolean
  819. return res
  820. case schemas.MediumInt, schemas.Int, schemas.Integer:
  821. if c.IsAutoIncrement {
  822. return schemas.Serial
  823. }
  824. return schemas.Integer
  825. case schemas.BigInt:
  826. if c.IsAutoIncrement {
  827. return schemas.BigSerial
  828. }
  829. return schemas.BigInt
  830. case schemas.Serial, schemas.BigSerial:
  831. c.IsAutoIncrement = true
  832. c.Nullable = false
  833. res = t
  834. case schemas.Binary, schemas.VarBinary:
  835. return schemas.Bytea
  836. case schemas.DateTime:
  837. res = schemas.TimeStamp
  838. case schemas.TimeStampz:
  839. return "timestamp with time zone"
  840. case schemas.Float:
  841. res = schemas.Real
  842. case schemas.TinyText, schemas.MediumText, schemas.LongText:
  843. res = schemas.Text
  844. case schemas.NVarchar:
  845. res = schemas.Varchar
  846. case schemas.Uuid:
  847. return schemas.Uuid
  848. case schemas.Blob, schemas.TinyBlob, schemas.MediumBlob, schemas.LongBlob:
  849. return schemas.Bytea
  850. case schemas.Double:
  851. return "DOUBLE PRECISION"
  852. default:
  853. if c.IsAutoIncrement {
  854. return schemas.Serial
  855. }
  856. res = t
  857. }
  858. if strings.EqualFold(res, "bool") {
  859. // for bool, we don't need length information
  860. return res
  861. }
  862. hasLen1 := (c.Length > 0)
  863. hasLen2 := (c.Length2 > 0)
  864. if hasLen2 {
  865. res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")"
  866. } else if hasLen1 {
  867. res += "(" + strconv.Itoa(c.Length) + ")"
  868. }
  869. return res
  870. }
  871. func (db *postgres) IsReserved(name string) bool {
  872. _, ok := postgresReservedWords[strings.ToUpper(name)]
  873. return ok
  874. }
  875. func (db *postgres) AutoIncrStr() string {
  876. return ""
  877. }
  878. func (db *postgres) CreateTableSQL(table *schemas.Table, tableName string) ([]string, bool) {
  879. var sql string
  880. sql = "CREATE TABLE IF NOT EXISTS "
  881. if tableName == "" {
  882. tableName = table.Name
  883. }
  884. quoter := db.Quoter()
  885. sql += quoter.Quote(tableName)
  886. sql += " ("
  887. if len(table.ColumnsSeq()) > 0 {
  888. pkList := table.PrimaryKeys
  889. for _, colName := range table.ColumnsSeq() {
  890. col := table.GetColumn(colName)
  891. if col.IsPrimaryKey && len(pkList) == 1 {
  892. sql += db.String(col)
  893. } else {
  894. sql += db.StringNoPk(col)
  895. }
  896. sql = strings.TrimSpace(sql)
  897. sql += ", "
  898. }
  899. if len(pkList) > 1 {
  900. sql += "PRIMARY KEY ( "
  901. sql += quoter.Join(pkList, ",")
  902. sql += " ), "
  903. }
  904. sql = sql[:len(sql)-2]
  905. }
  906. sql += ")"
  907. return []string{sql}, true
  908. }
  909. func (db *postgres) IndexCheckSQL(tableName, idxName string) (string, []interface{}) {
  910. if len(db.getSchema()) == 0 {
  911. args := []interface{}{tableName, idxName}
  912. return `SELECT indexname FROM pg_indexes WHERE tablename = ? AND indexname = ?`, args
  913. }
  914. args := []interface{}{db.getSchema(), tableName, idxName}
  915. return `SELECT indexname FROM pg_indexes ` +
  916. `WHERE schemaname = ? AND tablename = ? AND indexname = ?`, args
  917. }
  918. func (db *postgres) IsTableExist(queryer core.Queryer, ctx context.Context, tableName string) (bool, error) {
  919. if len(db.getSchema()) == 0 {
  920. return db.HasRecords(queryer, ctx, `SELECT tablename FROM pg_tables WHERE tablename = $1`, tableName)
  921. }
  922. return db.HasRecords(queryer, ctx, `SELECT tablename FROM pg_tables WHERE schemaname = $1 AND tablename = $2`,
  923. db.getSchema(), tableName)
  924. }
  925. func (db *postgres) ModifyColumnSQL(tableName string, col *schemas.Column) string {
  926. if len(db.getSchema()) == 0 || strings.Contains(tableName, ".") {
  927. return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s",
  928. tableName, col.Name, db.SQLType(col))
  929. }
  930. return fmt.Sprintf("alter table %s.%s ALTER COLUMN %s TYPE %s",
  931. db.getSchema(), tableName, col.Name, db.SQLType(col))
  932. }
  933. func (db *postgres) DropIndexSQL(tableName string, index *schemas.Index) string {
  934. idxName := index.Name
  935. tableParts := strings.Split(strings.Replace(tableName, `"`, "", -1), ".")
  936. tableName = tableParts[len(tableParts)-1]
  937. if !strings.HasPrefix(idxName, "UQE_") &&
  938. !strings.HasPrefix(idxName, "IDX_") {
  939. if index.Type == schemas.UniqueType {
  940. idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
  941. } else {
  942. idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
  943. }
  944. }
  945. if db.getSchema() != "" {
  946. idxName = db.getSchema() + "." + idxName
  947. }
  948. return fmt.Sprintf("DROP INDEX %v", db.Quoter().Quote(idxName))
  949. }
  950. func (db *postgres) IsColumnExist(queryer core.Queryer, ctx context.Context, tableName, colName string) (bool, error) {
  951. args := []interface{}{db.getSchema(), tableName, colName}
  952. query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = $1 AND table_name = $2" +
  953. " AND column_name = $3"
  954. if len(db.getSchema()) == 0 {
  955. args = []interface{}{tableName, colName}
  956. query = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" +
  957. " AND column_name = $2"
  958. }
  959. rows, err := queryer.QueryContext(ctx, query, args...)
  960. if err != nil {
  961. return false, err
  962. }
  963. defer rows.Close()
  964. return rows.Next(), nil
  965. }
  966. func (db *postgres) GetColumns(queryer core.Queryer, ctx context.Context, tableName string) ([]string, map[string]*schemas.Column, error) {
  967. args := []interface{}{tableName}
  968. s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length,
  969. CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey,
  970. CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey
  971. FROM pg_attribute f
  972. JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid
  973. LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum
  974. LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
  975. LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)
  976. LEFT JOIN pg_class AS g ON p.confrelid = g.oid
  977. LEFT JOIN INFORMATION_SCHEMA.COLUMNS s ON s.column_name=f.attname AND c.relname=s.table_name
  978. WHERE n.nspname= s.table_schema AND c.relkind = 'r'::char AND c.relname = $1%s AND f.attnum > 0 ORDER BY f.attnum;`
  979. schema := db.getSchema()
  980. if schema != "" {
  981. s = fmt.Sprintf(s, "AND s.table_schema = $2")
  982. args = append(args, schema)
  983. } else {
  984. s = fmt.Sprintf(s, "")
  985. }
  986. rows, err := queryer.QueryContext(ctx, s, args...)
  987. if err != nil {
  988. return nil, nil, err
  989. }
  990. defer rows.Close()
  991. cols := make(map[string]*schemas.Column)
  992. colSeq := make([]string, 0)
  993. for rows.Next() {
  994. col := new(schemas.Column)
  995. col.Indexes = make(map[string]int)
  996. var colName, isNullable, dataType string
  997. var maxLenStr, colDefault *string
  998. var isPK, isUnique bool
  999. err = rows.Scan(&colName, &colDefault, &isNullable, &dataType, &maxLenStr, &isPK, &isUnique)
  1000. if err != nil {
  1001. return nil, nil, err
  1002. }
  1003. var maxLen int
  1004. if maxLenStr != nil {
  1005. maxLen, err = strconv.Atoi(*maxLenStr)
  1006. if err != nil {
  1007. return nil, nil, err
  1008. }
  1009. }
  1010. col.Name = strings.Trim(colName, `" `)
  1011. if colDefault != nil {
  1012. var theDefault = *colDefault
  1013. // cockroach has type with the default value with :::
  1014. // and postgres with ::, we should remove them before store them
  1015. idx := strings.Index(theDefault, ":::")
  1016. if idx == -1 {
  1017. idx = strings.Index(theDefault, "::")
  1018. }
  1019. if idx > -1 {
  1020. theDefault = theDefault[:idx]
  1021. }
  1022. if strings.HasSuffix(theDefault, "+00:00'") {
  1023. theDefault = theDefault[:len(theDefault)-7] + "'"
  1024. }
  1025. col.Default = theDefault
  1026. col.DefaultIsEmpty = false
  1027. if strings.HasPrefix(col.Default, "nextval(") {
  1028. col.IsAutoIncrement = true
  1029. col.Default = ""
  1030. col.DefaultIsEmpty = true
  1031. }
  1032. } else {
  1033. col.DefaultIsEmpty = true
  1034. }
  1035. if isPK {
  1036. col.IsPrimaryKey = true
  1037. }
  1038. col.Nullable = (isNullable == "YES")
  1039. switch strings.ToLower(dataType) {
  1040. case "character varying", "character", "string":
  1041. col.SQLType = schemas.SQLType{Name: schemas.Varchar, DefaultLength: 0, DefaultLength2: 0}
  1042. case "timestamp without time zone":
  1043. col.SQLType = schemas.SQLType{Name: schemas.DateTime, DefaultLength: 0, DefaultLength2: 0}
  1044. case "timestamp with time zone":
  1045. col.SQLType = schemas.SQLType{Name: schemas.TimeStampz, DefaultLength: 0, DefaultLength2: 0}
  1046. case "double precision":
  1047. col.SQLType = schemas.SQLType{Name: schemas.Double, DefaultLength: 0, DefaultLength2: 0}
  1048. case "boolean":
  1049. col.SQLType = schemas.SQLType{Name: schemas.Bool, DefaultLength: 0, DefaultLength2: 0}
  1050. case "time without time zone":
  1051. col.SQLType = schemas.SQLType{Name: schemas.Time, DefaultLength: 0, DefaultLength2: 0}
  1052. case "bytes":
  1053. col.SQLType = schemas.SQLType{Name: schemas.Binary, DefaultLength: 0, DefaultLength2: 0}
  1054. case "oid":
  1055. col.SQLType = schemas.SQLType{Name: schemas.BigInt, DefaultLength: 0, DefaultLength2: 0}
  1056. case "array":
  1057. col.SQLType = schemas.SQLType{Name: schemas.Array, DefaultLength: 0, DefaultLength2: 0}
  1058. default:
  1059. startIdx := strings.Index(strings.ToLower(dataType), "string(")
  1060. if startIdx != -1 && strings.HasSuffix(dataType, ")") {
  1061. length := dataType[startIdx+8 : len(dataType)-1]
  1062. l, _ := strconv.Atoi(length)
  1063. col.SQLType = schemas.SQLType{Name: "STRING", DefaultLength: l, DefaultLength2: 0}
  1064. } else {
  1065. col.SQLType = schemas.SQLType{Name: strings.ToUpper(dataType), DefaultLength: 0, DefaultLength2: 0}
  1066. }
  1067. }
  1068. if _, ok := schemas.SqlTypes[col.SQLType.Name]; !ok {
  1069. return nil, nil, fmt.Errorf("Unknown colType: %s - %s", dataType, col.SQLType.Name)
  1070. }
  1071. col.Length = maxLen
  1072. if !col.DefaultIsEmpty {
  1073. if col.SQLType.IsText() {
  1074. if strings.HasSuffix(col.Default, "::character varying") {
  1075. col.Default = strings.TrimRight(col.Default, "::character varying")
  1076. } else if !strings.HasPrefix(col.Default, "'") {
  1077. col.Default = "'" + col.Default + "'"
  1078. }
  1079. } else if col.SQLType.IsTime() {
  1080. if strings.HasSuffix(col.Default, "::timestamp without time zone") {
  1081. col.Default = strings.TrimRight(col.Default, "::timestamp without time zone")
  1082. }
  1083. }
  1084. }
  1085. cols[col.Name] = col
  1086. colSeq = append(colSeq, col.Name)
  1087. }
  1088. return colSeq, cols, nil
  1089. }
  1090. func (db *postgres) GetTables(queryer core.Queryer, ctx context.Context) ([]*schemas.Table, error) {
  1091. args := []interface{}{}
  1092. s := "SELECT tablename FROM pg_tables"
  1093. schema := db.getSchema()
  1094. if schema != "" {
  1095. args = append(args, schema)
  1096. s = s + " WHERE schemaname = $1"
  1097. }
  1098. rows, err := queryer.QueryContext(ctx, s, args...)
  1099. if err != nil {
  1100. return nil, err
  1101. }
  1102. defer rows.Close()
  1103. tables := make([]*schemas.Table, 0)
  1104. for rows.Next() {
  1105. table := schemas.NewEmptyTable()
  1106. var name string
  1107. err = rows.Scan(&name)
  1108. if err != nil {
  1109. return nil, err
  1110. }
  1111. table.Name = name
  1112. tables = append(tables, table)
  1113. }
  1114. return tables, nil
  1115. }
  1116. func getIndexColName(indexdef string) []string {
  1117. var colNames []string
  1118. cs := strings.Split(indexdef, "(")
  1119. for _, v := range strings.Split(strings.Split(cs[1], ")")[0], ",") {
  1120. colNames = append(colNames, strings.Split(strings.TrimLeft(v, " "), " ")[0])
  1121. }
  1122. return colNames
  1123. }
  1124. func (db *postgres) GetIndexes(queryer core.Queryer, ctx context.Context, tableName string) (map[string]*schemas.Index, error) {
  1125. args := []interface{}{tableName}
  1126. s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE tablename=$1")
  1127. if len(db.getSchema()) != 0 {
  1128. args = append(args, db.getSchema())
  1129. s = s + " AND schemaname=$2"
  1130. }
  1131. rows, err := queryer.QueryContext(ctx, s, args...)
  1132. if err != nil {
  1133. return nil, err
  1134. }
  1135. defer rows.Close()
  1136. indexes := make(map[string]*schemas.Index, 0)
  1137. for rows.Next() {
  1138. var indexType int
  1139. var indexName, indexdef string
  1140. var colNames []string
  1141. err = rows.Scan(&indexName, &indexdef)
  1142. if err != nil {
  1143. return nil, err
  1144. }
  1145. if indexName == "primary" {
  1146. continue
  1147. }
  1148. indexName = strings.Trim(indexName, `" `)
  1149. if strings.HasSuffix(indexName, "_pkey") {
  1150. continue
  1151. }
  1152. if strings.HasPrefix(indexdef, "CREATE UNIQUE INDEX") {
  1153. indexType = schemas.UniqueType
  1154. } else {
  1155. indexType = schemas.IndexType
  1156. }
  1157. colNames = getIndexColName(indexdef)
  1158. var isRegular bool
  1159. if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) {
  1160. newIdxName := indexName[5+len(tableName):]
  1161. isRegular = true
  1162. if newIdxName != "" {
  1163. indexName = newIdxName
  1164. }
  1165. }
  1166. index := &schemas.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)}
  1167. for _, colName := range colNames {
  1168. index.Cols = append(index.Cols, strings.TrimSpace(strings.Replace(colName, `"`, "", -1)))
  1169. }
  1170. index.IsRegular = isRegular
  1171. indexes[index.Name] = index
  1172. }
  1173. return indexes, nil
  1174. }
  1175. func (db *postgres) Filters() []Filter {
  1176. return []Filter{&SeqFilter{Prefix: "$", Start: 1}}
  1177. }
  1178. type pqDriver struct {
  1179. }
  1180. type values map[string]string
  1181. func (vs values) Set(k, v string) {
  1182. vs[k] = v
  1183. }
  1184. func (vs values) Get(k string) (v string) {
  1185. return vs[k]
  1186. }
  1187. func parseURL(connstr string) (string, error) {
  1188. u, err := url.Parse(connstr)
  1189. if err != nil {
  1190. return "", err
  1191. }
  1192. if u.Scheme != "postgresql" && u.Scheme != "postgres" {
  1193. return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme)
  1194. }
  1195. escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
  1196. if u.Path != "" {
  1197. return escaper.Replace(u.Path[1:]), nil
  1198. }
  1199. return "", nil
  1200. }
  1201. func parseOpts(name string, o values) error {
  1202. if len(name) == 0 {
  1203. return fmt.Errorf("invalid options: %s", name)
  1204. }
  1205. name = strings.TrimSpace(name)
  1206. ps := strings.Split(name, " ")
  1207. for _, p := range ps {
  1208. kv := strings.Split(p, "=")
  1209. if len(kv) < 2 {
  1210. return fmt.Errorf("invalid option: %q", p)
  1211. }
  1212. o.Set(kv[0], kv[1])
  1213. }
  1214. return nil
  1215. }
  1216. func (p *pqDriver) Parse(driverName, dataSourceName string) (*URI, error) {
  1217. db := &URI{DBType: schemas.POSTGRES}
  1218. var err error
  1219. if strings.HasPrefix(dataSourceName, "postgresql://") || strings.HasPrefix(dataSourceName, "postgres://") {
  1220. db.DBName, err = parseURL(dataSourceName)
  1221. if err != nil {
  1222. return nil, err
  1223. }
  1224. } else {
  1225. o := make(values)
  1226. err = parseOpts(dataSourceName, o)
  1227. if err != nil {
  1228. return nil, err
  1229. }
  1230. db.DBName = o.Get("dbname")
  1231. }
  1232. if db.DBName == "" {
  1233. return nil, errors.New("dbname is empty")
  1234. }
  1235. return db, nil
  1236. }
  1237. type pqDriverPgx struct {
  1238. pqDriver
  1239. }
  1240. func (pgx *pqDriverPgx) Parse(driverName, dataSourceName string) (*URI, error) {
  1241. // Remove the leading characters for driver to work
  1242. if len(dataSourceName) >= 9 && dataSourceName[0] == 0 {
  1243. dataSourceName = dataSourceName[9:]
  1244. }
  1245. return pgx.pqDriver.Parse(driverName, dataSourceName)
  1246. }
  1247. // QueryDefaultPostgresSchema returns the default postgres schema
  1248. func QueryDefaultPostgresSchema(ctx context.Context, queryer core.Queryer) (string, error) {
  1249. rows, err := queryer.QueryContext(ctx, "SHOW SEARCH_PATH")
  1250. if err != nil {
  1251. return "", err
  1252. }
  1253. defer rows.Close()
  1254. if rows.Next() {
  1255. var defaultSchema string
  1256. if err = rows.Scan(&defaultSchema); err != nil {
  1257. return "", err
  1258. }
  1259. parts := strings.Split(defaultSchema, ",")
  1260. return strings.TrimSpace(parts[len(parts)-1]), nil
  1261. }
  1262. return "", errors.New("No default schema")
  1263. }