postgres.go 48 KB

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