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 52KB

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