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

postgres.go 48 kB

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