sql.el 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934
  1. ;;; sql.el --- specialized comint.el for SQL interpreters
  2. ;; Copyright (C) 1998-2012 Free Software Foundation, Inc.
  3. ;; Author: Alex Schroeder <alex@gnu.org>
  4. ;; Maintainer: Michael Mauger <mmaug@yahoo.com>
  5. ;; Version: 3.0
  6. ;; Keywords: comm languages processes
  7. ;; URL: http://savannah.gnu.org/projects/emacs/
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;; Please send bug reports and bug fixes to the mailing list at
  21. ;; help-gnu-emacs@gnu.org. If you want to subscribe to the mailing
  22. ;; list, see the web page at
  23. ;; http://lists.gnu.org/mailman/listinfo/help-gnu-emacs for
  24. ;; instructions. I monitor this list actively. If you send an e-mail
  25. ;; to Alex Schroeder it usually makes it to me when Alex has a chance
  26. ;; to forward them along (Thanks, Alex).
  27. ;; This file provides a sql-mode and a sql-interactive-mode. The
  28. ;; original goals were two simple modes providing syntactic
  29. ;; highlighting. The interactive mode had to provide a command-line
  30. ;; history; the other mode had to provide "send region/buffer to SQL
  31. ;; interpreter" functions. "simple" in this context means easy to
  32. ;; use, easy to maintain and little or no bells and whistles. This
  33. ;; has changed somewhat as experience with the mode has accumulated.
  34. ;; Support for different flavors of SQL and command interpreters was
  35. ;; available in early versions of sql.el. This support has been
  36. ;; extended and formalized in later versions. Part of the impetus for
  37. ;; the improved support of SQL flavors was borne out of the current
  38. ;; maintainers consulting experience. In the past twenty years, I
  39. ;; have used Oracle, Sybase, Informix, MySQL, Postgres, and SQLServer.
  40. ;; On some assignments, I have used two or more of these concurrently.
  41. ;; If anybody feels like extending this sql mode, take a look at the
  42. ;; above mentioned modes and write a sqlx-mode on top of this one. If
  43. ;; this proves to be difficult, please suggest changes that will
  44. ;; facilitate your plans. Facilities have been provided to add
  45. ;; products and product-specific configuration.
  46. ;; sql-interactive-mode is used to interact with a SQL interpreter
  47. ;; process in a SQLi buffer (usually called `*SQL*'). The SQLi buffer
  48. ;; is created by calling a SQL interpreter-specific entry function or
  49. ;; sql-product-interactive. Do *not* call sql-interactive-mode by
  50. ;; itself.
  51. ;; The list of currently supported interpreters and the corresponding
  52. ;; entry function used to create the SQLi buffers is shown with
  53. ;; `sql-help' (M-x sql-help).
  54. ;; Since sql-interactive-mode is built on top of the general
  55. ;; command-interpreter-in-a-buffer mode (comint mode), it shares a
  56. ;; common base functionality, and a common set of bindings, with all
  57. ;; modes derived from comint mode. This makes these modes easier to
  58. ;; use.
  59. ;; sql-mode can be used to keep editing SQL statements. The SQL
  60. ;; statements can be sent to the SQL process in the SQLi buffer.
  61. ;; For documentation on the functionality provided by comint mode, and
  62. ;; the hooks available for customizing it, see the file `comint.el'.
  63. ;; Hint for newbies: take a look at `dabbrev-expand', `abbrev-mode', and
  64. ;; `imenu-add-menubar-index'.
  65. ;;; Requirements for Emacs 19.34:
  66. ;; If you are using Emacs 19.34, you will have to get and install
  67. ;; the file regexp-opt.el
  68. ;; <URL:ftp://ftp.ifi.uio.no/pub/emacs/emacs-20.3/lisp/emacs-lisp/regexp-opt.el>
  69. ;; and the custom package
  70. ;; <URL:http://www.dina.kvl.dk/~abraham/custom/>.
  71. ;;; Bugs:
  72. ;; sql-ms now uses osql instead of isql. Osql flushes its error
  73. ;; stream more frequently than isql so that error messages are
  74. ;; available. There is no prompt and some output still is buffered.
  75. ;; This improves the interaction under Emacs but it still is somewhat
  76. ;; awkward.
  77. ;; Quoted identifiers are not supported for highlighting. Most
  78. ;; databases support the use of double quoted strings in place of
  79. ;; identifiers; ms (Microsoft SQLServer) also supports identifiers
  80. ;; enclosed within brackets [].
  81. ;;; Product Support:
  82. ;; To add support for additional SQL products the following steps
  83. ;; must be followed ("xyz" is the name of the product in the examples
  84. ;; below):
  85. ;; 1) Add the product to the list of known products.
  86. ;; (sql-add-product 'xyz "XyzDB"
  87. ;; '(:free-software t))
  88. ;; 2) Define font lock settings. All ANSI keywords will be
  89. ;; highlighted automatically, so only product specific keywords
  90. ;; need to be defined here.
  91. ;; (defvar my-sql-mode-xyz-font-lock-keywords
  92. ;; '(("\\b\\(red\\|orange\\|yellow\\)\\b"
  93. ;; . font-lock-keyword-face))
  94. ;; "XyzDB SQL keywords used by font-lock.")
  95. ;; (sql-set-product-feature 'xyz
  96. ;; :font-lock
  97. ;; 'my-sql-mode-xyz-font-lock-keywords)
  98. ;; 3) Define any special syntax characters including comments and
  99. ;; identifier characters.
  100. ;; (sql-set-product-feature 'xyz
  101. ;; :syntax-alist ((?# . "_")))
  102. ;; 4) Define the interactive command interpreter for the database
  103. ;; product.
  104. ;; (defcustom my-sql-xyz-program "ixyz"
  105. ;; "Command to start ixyz by XyzDB."
  106. ;; :type 'file
  107. ;; :group 'SQL)
  108. ;;
  109. ;; (sql-set-product-feature 'xyz
  110. ;; :sqli-program 'my-sql-xyz-program)
  111. ;; (sql-set-product-feature 'xyz
  112. ;; :prompt-regexp "^xyzdb> ")
  113. ;; (sql-set-product-feature 'xyz
  114. ;; :prompt-length 7)
  115. ;; 5) Define login parameters and command line formatting.
  116. ;; (defcustom my-sql-xyz-login-params '(user password server database)
  117. ;; "Login parameters to needed to connect to XyzDB."
  118. ;; :type 'sql-login-params
  119. ;; :group 'SQL)
  120. ;;
  121. ;; (sql-set-product-feature 'xyz
  122. ;; :sqli-login 'my-sql-xyz-login-params)
  123. ;; (defcustom my-sql-xyz-options '("-X" "-Y" "-Z")
  124. ;; "List of additional options for `sql-xyz-program'."
  125. ;; :type '(repeat string)
  126. ;; :group 'SQL)
  127. ;;
  128. ;; (sql-set-product-feature 'xyz
  129. ;; :sqli-options 'my-sql-xyz-options))
  130. ;; (defun my-sql-comint-xyz (product options)
  131. ;; "Connect ti XyzDB in a comint buffer."
  132. ;;
  133. ;; ;; Do something with `sql-user', `sql-password',
  134. ;; ;; `sql-database', and `sql-server'.
  135. ;; (let ((params options))
  136. ;; (if (not (string= "" sql-server))
  137. ;; (setq params (append (list "-S" sql-server) params)))
  138. ;; (if (not (string= "" sql-database))
  139. ;; (setq params (append (list "-D" sql-database) params)))
  140. ;; (if (not (string= "" sql-password))
  141. ;; (setq params (append (list "-P" sql-password) params)))
  142. ;; (if (not (string= "" sql-user))
  143. ;; (setq params (append (list "-U" sql-user) params)))
  144. ;; (sql-comint product params)))
  145. ;;
  146. ;; (sql-set-product-feature 'xyz
  147. ;; :sqli-comint-func 'my-sql-comint-xyz)
  148. ;; 6) Define a convenience function to invoke the SQL interpreter.
  149. ;; (defun my-sql-xyz (&optional buffer)
  150. ;; "Run ixyz by XyzDB as an inferior process."
  151. ;; (interactive "P")
  152. ;; (sql-product-interactive 'xyz buffer))
  153. ;;; To Do:
  154. ;; Improve keyword highlighting for individual products. I have tried
  155. ;; to update those database that I use. Feel free to send me updates,
  156. ;; or direct me to the reference manuals for your favorite database.
  157. ;; When there are no keywords defined, the ANSI keywords are
  158. ;; highlighted. ANSI keywords are highlighted even if the keyword is
  159. ;; not used for your current product. This should help identify
  160. ;; portability concerns.
  161. ;; Add different highlighting levels.
  162. ;; Add support for listing available tables or the columns in a table.
  163. ;;; Thanks to all the people who helped me out:
  164. ;; Alex Schroeder <alex@gnu.org> -- the original author
  165. ;; Kai Blauberg <kai.blauberg@metla.fi>
  166. ;; <ibalaban@dalet.com>
  167. ;; Yair Friedman <yfriedma@JohnBryce.Co.Il>
  168. ;; Gregor Zych <zych@pool.informatik.rwth-aachen.de>
  169. ;; nino <nino@inform.dk>
  170. ;; Berend de Boer <berend@pobox.com>
  171. ;; Adam Jenkins <adam@thejenkins.org>
  172. ;; Michael Mauger <mmaug@yahoo.com> -- improved product support
  173. ;; Drew Adams <drew.adams@oracle.com> -- Emacs 20 support
  174. ;; Harald Maier <maierh@myself.com> -- sql-send-string
  175. ;; Stefan Monnier <monnier@iro.umontreal.ca> -- font-lock corrections; code polish
  176. ;; Paul Sleigh <bat@flurf.net> -- MySQL keyword enhancement
  177. ;; Andrew Schein <andrew@andrewschein.com> -- sql-port bug
  178. ;;; Code:
  179. (require 'comint)
  180. ;; Need the following to allow GNU Emacs 19 to compile the file.
  181. (eval-when-compile
  182. (require 'regexp-opt))
  183. (require 'custom)
  184. (require 'thingatpt)
  185. (eval-when-compile ;; needed in Emacs 19, 20
  186. (setq max-specpdl-size (max max-specpdl-size 2000)))
  187. (defun sql-signum (n)
  188. "Return 1, 0, or -1 to identify the sign of N."
  189. (cond
  190. ((not (numberp n)) nil)
  191. ((< n 0) -1)
  192. ((> n 0) 1)
  193. (t 0)))
  194. (defvar font-lock-keyword-face)
  195. (defvar font-lock-set-defaults)
  196. (defvar font-lock-string-face)
  197. ;;; Allow customization
  198. (defgroup SQL nil
  199. "Running a SQL interpreter from within Emacs buffers."
  200. :version "20.4"
  201. :group 'languages
  202. :group 'processes)
  203. ;; These four variables will be used as defaults, if set.
  204. (defcustom sql-user ""
  205. "Default username."
  206. :type 'string
  207. :group 'SQL
  208. :safe 'stringp)
  209. (defcustom sql-password ""
  210. "Default password.
  211. Storing your password in a textfile such as ~/.emacs could be dangerous.
  212. Customizing your password will store it in your ~/.emacs file."
  213. :type 'string
  214. :group 'SQL
  215. :risky t)
  216. (defcustom sql-database ""
  217. "Default database."
  218. :type 'string
  219. :group 'SQL
  220. :safe 'stringp)
  221. (defcustom sql-server ""
  222. "Default server or host."
  223. :type 'string
  224. :group 'SQL
  225. :safe 'stringp)
  226. (defcustom sql-port 0
  227. "Default port for connecting to a MySQL or Postgres server."
  228. :version "24.1"
  229. :type 'number
  230. :group 'SQL
  231. :safe 'numberp)
  232. ;; Login parameter type
  233. (define-widget 'sql-login-params 'lazy
  234. "Widget definition of the login parameters list"
  235. ;; FIXME: does not implement :default property for the user,
  236. ;; database and server options. Anybody have some guidance on how to
  237. ;; do this.
  238. :tag "Login Parameters"
  239. :type '(repeat (choice
  240. (const user)
  241. (const password)
  242. (choice :tag "server"
  243. (const server)
  244. (list :tag "file"
  245. (const :format "" server)
  246. (const :format "" :file)
  247. regexp)
  248. (list :tag "completion"
  249. (const :format "" server)
  250. (const :format "" :completion)
  251. (restricted-sexp
  252. :match-alternatives (listp stringp))))
  253. (choice :tag "database"
  254. (const database)
  255. (list :tag "file"
  256. (const :format "" database)
  257. (const :format "" :file)
  258. regexp)
  259. (list :tag "completion"
  260. (const :format "" database)
  261. (const :format "" :completion)
  262. (restricted-sexp
  263. :match-alternatives (listp stringp))))
  264. (const port))))
  265. ;; SQL Product support
  266. (defvar sql-interactive-product nil
  267. "Product under `sql-interactive-mode'.")
  268. (defvar sql-connection nil
  269. "Connection name if interactive session started by `sql-connect'.")
  270. (defvar sql-product-alist
  271. '((ansi
  272. :name "ANSI"
  273. :font-lock sql-mode-ansi-font-lock-keywords
  274. :statement sql-ansi-statement-starters)
  275. (db2
  276. :name "DB2"
  277. :font-lock sql-mode-db2-font-lock-keywords
  278. :sqli-program sql-db2-program
  279. :sqli-options sql-db2-options
  280. :sqli-login sql-db2-login-params
  281. :sqli-comint-func sql-comint-db2
  282. :prompt-regexp "^db2 => "
  283. :prompt-length 7
  284. :prompt-cont-regexp "^db2 (cont\.) => "
  285. :input-filter sql-escape-newlines-filter)
  286. (informix
  287. :name "Informix"
  288. :font-lock sql-mode-informix-font-lock-keywords
  289. :sqli-program sql-informix-program
  290. :sqli-options sql-informix-options
  291. :sqli-login sql-informix-login-params
  292. :sqli-comint-func sql-comint-informix
  293. :prompt-regexp "^> "
  294. :prompt-length 2
  295. :syntax-alist ((?{ . "<") (?} . ">")))
  296. (ingres
  297. :name "Ingres"
  298. :font-lock sql-mode-ingres-font-lock-keywords
  299. :sqli-program sql-ingres-program
  300. :sqli-options sql-ingres-options
  301. :sqli-login sql-ingres-login-params
  302. :sqli-comint-func sql-comint-ingres
  303. :prompt-regexp "^\* "
  304. :prompt-length 2
  305. :prompt-cont-regexp "^\* ")
  306. (interbase
  307. :name "Interbase"
  308. :font-lock sql-mode-interbase-font-lock-keywords
  309. :sqli-program sql-interbase-program
  310. :sqli-options sql-interbase-options
  311. :sqli-login sql-interbase-login-params
  312. :sqli-comint-func sql-comint-interbase
  313. :prompt-regexp "^SQL> "
  314. :prompt-length 5)
  315. (linter
  316. :name "Linter"
  317. :font-lock sql-mode-linter-font-lock-keywords
  318. :sqli-program sql-linter-program
  319. :sqli-options sql-linter-options
  320. :sqli-login sql-linter-login-params
  321. :sqli-comint-func sql-comint-linter
  322. :prompt-regexp "^SQL>"
  323. :prompt-length 4)
  324. (ms
  325. :name "Microsoft"
  326. :font-lock sql-mode-ms-font-lock-keywords
  327. :sqli-program sql-ms-program
  328. :sqli-options sql-ms-options
  329. :sqli-login sql-ms-login-params
  330. :sqli-comint-func sql-comint-ms
  331. :prompt-regexp "^[0-9]*>"
  332. :prompt-length 5
  333. :syntax-alist ((?@ . "_"))
  334. :terminator ("^go" . "go"))
  335. (mysql
  336. :name "MySQL"
  337. :free-software t
  338. :font-lock sql-mode-mysql-font-lock-keywords
  339. :sqli-program sql-mysql-program
  340. :sqli-options sql-mysql-options
  341. :sqli-login sql-mysql-login-params
  342. :sqli-comint-func sql-comint-mysql
  343. :list-all "SHOW TABLES;"
  344. :list-table "DESCRIBE %s;"
  345. :prompt-regexp "^mysql> "
  346. :prompt-length 6
  347. :prompt-cont-regexp "^ -> "
  348. :syntax-alist ((?# . "< b"))
  349. :input-filter sql-remove-tabs-filter)
  350. (oracle
  351. :name "Oracle"
  352. :font-lock sql-mode-oracle-font-lock-keywords
  353. :sqli-program sql-oracle-program
  354. :sqli-options sql-oracle-options
  355. :sqli-login sql-oracle-login-params
  356. :sqli-comint-func sql-comint-oracle
  357. :list-all sql-oracle-list-all
  358. :list-table sql-oracle-list-table
  359. :completion-object sql-oracle-completion-object
  360. :prompt-regexp "^SQL> "
  361. :prompt-length 5
  362. :prompt-cont-regexp "^\\s-*[[:digit:]]+ "
  363. :statement sql-oracle-statement-starters
  364. :syntax-alist ((?$ . "_") (?# . "_"))
  365. :terminator ("\\(^/\\|;\\)$" . "/")
  366. :input-filter sql-placeholders-filter)
  367. (postgres
  368. :name "Postgres"
  369. :free-software t
  370. :font-lock sql-mode-postgres-font-lock-keywords
  371. :sqli-program sql-postgres-program
  372. :sqli-options sql-postgres-options
  373. :sqli-login sql-postgres-login-params
  374. :sqli-comint-func sql-comint-postgres
  375. :list-all ("\\d+" . "\\dS+")
  376. :list-table ("\\d+ %s" . "\\dS+ %s")
  377. :completion-object sql-postgres-completion-object
  378. :prompt-regexp "^\\w*=[#>] "
  379. :prompt-length 5
  380. :prompt-cont-regexp "^\\w*[-(][#>] "
  381. :input-filter sql-remove-tabs-filter
  382. :terminator ("\\(^\\s-*\\\\g$\\|;\\)" . "\\g"))
  383. (solid
  384. :name "Solid"
  385. :font-lock sql-mode-solid-font-lock-keywords
  386. :sqli-program sql-solid-program
  387. :sqli-options sql-solid-options
  388. :sqli-login sql-solid-login-params
  389. :sqli-comint-func sql-comint-solid
  390. :prompt-regexp "^"
  391. :prompt-length 0)
  392. (sqlite
  393. :name "SQLite"
  394. :free-software t
  395. :font-lock sql-mode-sqlite-font-lock-keywords
  396. :sqli-program sql-sqlite-program
  397. :sqli-options sql-sqlite-options
  398. :sqli-login sql-sqlite-login-params
  399. :sqli-comint-func sql-comint-sqlite
  400. :list-all ".tables"
  401. :list-table ".schema %s"
  402. :completion-object sql-sqlite-completion-object
  403. :prompt-regexp "^sqlite> "
  404. :prompt-length 8
  405. :prompt-cont-regexp "^ \.\.\.> "
  406. :terminator ";")
  407. (sybase
  408. :name "Sybase"
  409. :font-lock sql-mode-sybase-font-lock-keywords
  410. :sqli-program sql-sybase-program
  411. :sqli-options sql-sybase-options
  412. :sqli-login sql-sybase-login-params
  413. :sqli-comint-func sql-comint-sybase
  414. :prompt-regexp "^SQL> "
  415. :prompt-length 5
  416. :syntax-alist ((?@ . "_"))
  417. :terminator ("^go" . "go"))
  418. )
  419. "An alist of product specific configuration settings.
  420. Without an entry in this list a product will not be properly
  421. highlighted and will not support `sql-interactive-mode'.
  422. Each element in the list is in the following format:
  423. \(PRODUCT FEATURE VALUE ...)
  424. where PRODUCT is the appropriate value of `sql-product'. The
  425. product name is then followed by FEATURE-VALUE pairs. If a
  426. FEATURE is not specified, its VALUE is treated as nil. FEATURE
  427. may be any one of the following:
  428. :name string containing the displayable name of
  429. the product.
  430. :free-software is the product Free (as in Freedom) software?
  431. :font-lock name of the variable containing the product
  432. specific font lock highlighting patterns.
  433. :sqli-program name of the variable containing the product
  434. specific interactive program name.
  435. :sqli-options name of the variable containing the list
  436. of product specific options.
  437. :sqli-login name of the variable containing the list of
  438. login parameters (i.e., user, password,
  439. database and server) needed to connect to
  440. the database.
  441. :sqli-comint-func name of a function which accepts no
  442. parameters that will use the values of
  443. `sql-user', `sql-password',
  444. `sql-database', `sql-server' and
  445. `sql-port' to open a comint buffer and
  446. connect to the database. Do product
  447. specific configuration of comint in this
  448. function.
  449. :list-all Command string or function which produces
  450. a listing of all objects in the database.
  451. If it's a cons cell, then the car
  452. produces the standard list of objects and
  453. the cdr produces an enhanced list of
  454. objects. What \"enhanced\" means is
  455. dependent on the SQL product and may not
  456. exist. In general though, the
  457. \"enhanced\" list should include visible
  458. objects from other schemas.
  459. :list-table Command string or function which produces
  460. a detailed listing of a specific database
  461. table. If its a cons cell, then the car
  462. produces the standard list and the cdr
  463. produces an enhanced list.
  464. :completion-object A function that returns a list of
  465. objects. Called with a single
  466. parameter--if nil then list objects
  467. accessible in the current schema, if
  468. not-nil it is the name of a schema whose
  469. objects should be listed.
  470. :completion-column A function that returns a list of
  471. columns. Called with a single
  472. parameter--if nil then list objects
  473. accessible in the current schema, if
  474. not-nil it is the name of a schema whose
  475. objects should be listed.
  476. :prompt-regexp regular expression string that matches
  477. the prompt issued by the product
  478. interpreter.
  479. :prompt-length length of the prompt on the line.
  480. :prompt-cont-regexp regular expression string that matches
  481. the continuation prompt issued by the
  482. product interpreter.
  483. :input-filter function which can filter strings sent to
  484. the command interpreter. It is also used
  485. by the `sql-send-string',
  486. `sql-send-region', `sql-send-paragraph'
  487. and `sql-send-buffer' functions. The
  488. function is passed the string sent to the
  489. command interpreter and must return the
  490. filtered string. May also be a list of
  491. such functions.
  492. :statement name of a variable containing a regexp that
  493. matches the beginning of SQL statements.
  494. :terminator the terminator to be sent after a
  495. `sql-send-string', `sql-send-region',
  496. `sql-send-paragraph' and
  497. `sql-send-buffer' command. May be the
  498. literal string or a cons of a regexp to
  499. match an existing terminator in the
  500. string and the terminator to be used if
  501. its absent. By default \";\".
  502. :syntax-alist alist of syntax table entries to enable
  503. special character treatment by font-lock
  504. and imenu.
  505. Other features can be stored but they will be ignored. However,
  506. you can develop new functionality which is product independent by
  507. using `sql-get-product-feature' to lookup the product specific
  508. settings.")
  509. (defvar sql-indirect-features
  510. '(:font-lock :sqli-program :sqli-options :sqli-login :statement))
  511. (defcustom sql-connection-alist nil
  512. "An alist of connection parameters for interacting with a SQL product.
  513. Each element of the alist is as follows:
  514. \(CONNECTION \(SQL-VARIABLE VALUE) ...)
  515. Where CONNECTION is a symbol identifying the connection, SQL-VARIABLE
  516. is the symbol name of a SQL mode variable, and VALUE is the value to
  517. be assigned to the variable. The most common SQL-VARIABLE settings
  518. associated with a connection are: `sql-product', `sql-user',
  519. `sql-password', `sql-port', `sql-server', and `sql-database'.
  520. If a SQL-VARIABLE is part of the connection, it will not be
  521. prompted for during login. The command `sql-connect' starts a
  522. predefined SQLi session using the parameters from this list.
  523. Connections defined here appear in the submenu SQL->Start... for
  524. making new SQLi sessions."
  525. :type `(alist :key-type (string :tag "Connection")
  526. :value-type
  527. (set
  528. (group (const :tag "Product" sql-product)
  529. (choice
  530. ,@(mapcar (lambda (prod-info)
  531. `(const :tag
  532. ,(or (plist-get (cdr prod-info) :name)
  533. (capitalize (symbol-name (car prod-info))))
  534. (quote ,(car prod-info))))
  535. sql-product-alist)))
  536. (group (const :tag "Username" sql-user) string)
  537. (group (const :tag "Password" sql-password) string)
  538. (group (const :tag "Server" sql-server) string)
  539. (group (const :tag "Database" sql-database) string)
  540. (group (const :tag "Port" sql-port) integer)
  541. (repeat :inline t
  542. (list :tab "Other"
  543. (symbol :tag " Variable Symbol")
  544. (sexp :tag "Value Expression")))))
  545. :version "24.1"
  546. :group 'SQL)
  547. (defcustom sql-product 'ansi
  548. "Select the SQL database product used so that buffers can be
  549. highlighted properly when you open them."
  550. :type `(choice
  551. ,@(mapcar (lambda (prod-info)
  552. `(const :tag
  553. ,(or (plist-get (cdr prod-info) :name)
  554. (capitalize (symbol-name (car prod-info))))
  555. ,(car prod-info)))
  556. sql-product-alist))
  557. :group 'SQL
  558. :safe 'symbolp)
  559. (defvaralias 'sql-dialect 'sql-product)
  560. ;; misc customization of sql.el behavior
  561. (defcustom sql-electric-stuff nil
  562. "Treat some input as electric.
  563. If set to the symbol `semicolon', then hitting `;' will send current
  564. input in the SQLi buffer to the process.
  565. If set to the symbol `go', then hitting `go' on a line by itself will
  566. send current input in the SQLi buffer to the process.
  567. If set to nil, then you must use \\[comint-send-input] in order to send
  568. current input in the SQLi buffer to the process."
  569. :type '(choice (const :tag "Nothing" nil)
  570. (const :tag "The semicolon `;'" semicolon)
  571. (const :tag "The string `go' by itself" go))
  572. :version "20.8"
  573. :group 'SQL)
  574. (defcustom sql-send-terminator nil
  575. "When non-nil, add a terminator to text sent to the SQL interpreter.
  576. When text is sent to the SQL interpreter (via `sql-send-string',
  577. `sql-send-region', `sql-send-paragraph' or `sql-send-buffer'), a
  578. command terminator can be automatically sent as well. The
  579. terminator is not sent, if the string sent already ends with the
  580. terminator.
  581. If this value is t, then the default command terminator for the
  582. SQL interpreter is sent. If this value is a string, then the
  583. string is sent.
  584. If the value is a cons cell of the form (PAT . TERM), then PAT is
  585. a regexp used to match the terminator in the string and TERM is
  586. the terminator to be sent. This form is useful if the SQL
  587. interpreter has more than one way of submitting a SQL command.
  588. The PAT regexp can match any of them, and TERM is the way we do
  589. it automatically."
  590. :type '(choice (const :tag "No Terminator" nil)
  591. (const :tag "Default Terminator" t)
  592. (string :tag "Terminator String")
  593. (cons :tag "Terminator Pattern and String"
  594. (string :tag "Terminator Pattern")
  595. (string :tag "Terminator String")))
  596. :version "22.2"
  597. :group 'SQL)
  598. (defvar sql-contains-names nil
  599. "When non-nil, the current buffer contains database names.
  600. Globally should be set to nil; it will be non-nil in `sql-mode',
  601. `sql-interactive-mode' and list all buffers.")
  602. (defcustom sql-pop-to-buffer-after-send-region nil
  603. "When non-nil, pop to the buffer SQL statements are sent to.
  604. After a call to `sql-sent-string', `sql-send-region',
  605. `sql-send-paragraph' or `sql-send-buffer', the window is split
  606. and the SQLi buffer is shown. If this variable is not nil, that
  607. buffer's window will be selected by calling `pop-to-buffer'. If
  608. this variable is nil, that buffer is shown using
  609. `display-buffer'."
  610. :type 'boolean
  611. :group 'SQL)
  612. ;; imenu support for sql-mode.
  613. (defvar sql-imenu-generic-expression
  614. ;; Items are in reverse order because they are rendered in reverse.
  615. '(("Rules/Defaults" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*\\(rule\\|default\\)\\s-+\\(\\w+\\)" 3)
  616. ("Sequences" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*sequence\\s-+\\(\\w+\\)" 2)
  617. ("Triggers" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*trigger\\s-+\\(\\w+\\)" 2)
  618. ("Functions" "^\\s-*\\(create\\s-+\\(\\w+\\s-+\\)*\\)?function\\s-+\\(\\w+\\)" 3)
  619. ("Procedures" "^\\s-*\\(create\\s-+\\(\\w+\\s-+\\)*\\)?proc\\(edure\\)?\\s-+\\(\\w+\\)" 4)
  620. ("Packages" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*package\\s-+\\(body\\s-+\\)?\\(\\w+\\)" 3)
  621. ("Types" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*type\\s-+\\(body\\s-+\\)?\\(\\w+\\)" 3)
  622. ("Indexes" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*index\\s-+\\(\\w+\\)" 2)
  623. ("Tables/Views" "^\\s-*create\\s-+\\(\\w+\\s-+\\)*\\(table\\|view\\)\\s-+\\(\\w+\\)" 3))
  624. "Define interesting points in the SQL buffer for `imenu'.
  625. This is used to set `imenu-generic-expression' when SQL mode is
  626. entered. Subsequent changes to `sql-imenu-generic-expression' will
  627. not affect existing SQL buffers because imenu-generic-expression is
  628. a local variable.")
  629. ;; history file
  630. (defcustom sql-input-ring-file-name nil
  631. "If non-nil, name of the file to read/write input history.
  632. You have to set this variable if you want the history of your commands
  633. saved from one Emacs session to the next. If this variable is set,
  634. exiting the SQL interpreter in an SQLi buffer will write the input
  635. history to the specified file. Starting a new process in a SQLi buffer
  636. will read the input history from the specified file.
  637. This is used to initialize `comint-input-ring-file-name'.
  638. Note that the size of the input history is determined by the variable
  639. `comint-input-ring-size'."
  640. :type '(choice (const :tag "none" nil)
  641. (file))
  642. :group 'SQL)
  643. (defcustom sql-input-ring-separator "\n--\n"
  644. "Separator between commands in the history file.
  645. If set to \"\\n\", each line in the history file will be interpreted as
  646. one command. Multi-line commands are split into several commands when
  647. the input ring is initialized from a history file.
  648. This variable used to initialize `comint-input-ring-separator'.
  649. `comint-input-ring-separator' is part of Emacs 21; if your Emacs
  650. does not have it, setting `sql-input-ring-separator' will have no
  651. effect. In that case multiline commands will be split into several
  652. commands when the input history is read, as if you had set
  653. `sql-input-ring-separator' to \"\\n\"."
  654. :type 'string
  655. :group 'SQL)
  656. ;; The usual hooks
  657. (defcustom sql-interactive-mode-hook '()
  658. "Hook for customizing `sql-interactive-mode'."
  659. :type 'hook
  660. :group 'SQL)
  661. (defcustom sql-mode-hook '()
  662. "Hook for customizing `sql-mode'."
  663. :type 'hook
  664. :group 'SQL)
  665. (defcustom sql-set-sqli-hook '()
  666. "Hook for reacting to changes of `sql-buffer'.
  667. This is called by `sql-set-sqli-buffer' when the value of `sql-buffer'
  668. is changed."
  669. :type 'hook
  670. :group 'SQL)
  671. (defcustom sql-login-hook '()
  672. "Hook for interacting with a buffer in `sql-interactive-mode'.
  673. This hook is invoked in a buffer once it is ready to accept input
  674. for the first time."
  675. :version "24.1"
  676. :type 'hook
  677. :group 'SQL)
  678. ;; Customization for ANSI
  679. (defcustom sql-ansi-statement-starters (regexp-opt '(
  680. "create" "alter" "drop"
  681. "select" "insert" "update" "delete" "merge"
  682. "grant" "revoke"
  683. ))
  684. "Regexp of keywords that start SQL commands
  685. All products share this list; products should define a regexp to
  686. identify additional keywords in a variable defined by
  687. the :statement feature."
  688. :version "24.1"
  689. :type 'string
  690. :group 'SQL)
  691. ;; Customization for Oracle
  692. (defcustom sql-oracle-program "sqlplus"
  693. "Command to start sqlplus by Oracle.
  694. Starts `sql-interactive-mode' after doing some setup.
  695. On Windows, \"sqlplus\" usually starts the sqlplus \"GUI\". In order
  696. to start the sqlplus console, use \"plus33\" or something similar.
  697. You will find the file in your Orant\\bin directory."
  698. :type 'file
  699. :group 'SQL)
  700. (defcustom sql-oracle-options nil
  701. "List of additional options for `sql-oracle-program'."
  702. :type '(repeat string)
  703. :version "20.8"
  704. :group 'SQL)
  705. (defcustom sql-oracle-login-params '(user password database)
  706. "List of login parameters needed to connect to Oracle."
  707. :type 'sql-login-params
  708. :version "24.1"
  709. :group 'SQL)
  710. (defcustom sql-oracle-statement-starters
  711. (regexp-opt '("declare" "begin" "with"))
  712. "Additional statement starting keywords in Oracle."
  713. :version "24.1"
  714. :type 'string
  715. :group 'SQL)
  716. (defcustom sql-oracle-scan-on t
  717. "Non-nil if placeholders should be replaced in Oracle SQLi.
  718. When non-nil, Emacs will scan text sent to sqlplus and prompt
  719. for replacement text for & placeholders as sqlplus does. This
  720. is needed on Windows where SQL*Plus output is buffered and the
  721. prompts are not shown until after the text is entered.
  722. You need to issue the following command in SQL*Plus to be safe:
  723. SET DEFINE OFF
  724. In older versions of SQL*Plus, this was the SET SCAN OFF command."
  725. :version "24.1"
  726. :type 'boolean
  727. :group 'SQL)
  728. ;; Customization for SQLite
  729. (defcustom sql-sqlite-program (or (executable-find "sqlite3")
  730. (executable-find "sqlite")
  731. "sqlite")
  732. "Command to start SQLite.
  733. Starts `sql-interactive-mode' after doing some setup."
  734. :type 'file
  735. :group 'SQL)
  736. (defcustom sql-sqlite-options nil
  737. "List of additional options for `sql-sqlite-program'."
  738. :type '(repeat string)
  739. :version "20.8"
  740. :group 'SQL)
  741. (defcustom sql-sqlite-login-params '((database :file ".*\\.\\(db\\|sqlite[23]?\\)"))
  742. "List of login parameters needed to connect to SQLite."
  743. :type 'sql-login-params
  744. :version "24.1"
  745. :group 'SQL)
  746. ;; Customization for MySQL
  747. (defcustom sql-mysql-program "mysql"
  748. "Command to start mysql by TcX.
  749. Starts `sql-interactive-mode' after doing some setup."
  750. :type 'file
  751. :group 'SQL)
  752. (defcustom sql-mysql-options nil
  753. "List of additional options for `sql-mysql-program'.
  754. The following list of options is reported to make things work
  755. on Windows: \"-C\" \"-t\" \"-f\" \"-n\"."
  756. :type '(repeat string)
  757. :version "20.8"
  758. :group 'SQL)
  759. (defcustom sql-mysql-login-params '(user password database server)
  760. "List of login parameters needed to connect to MySQL."
  761. :type 'sql-login-params
  762. :version "24.1"
  763. :group 'SQL)
  764. ;; Customization for Solid
  765. (defcustom sql-solid-program "solsql"
  766. "Command to start SOLID SQL Editor.
  767. Starts `sql-interactive-mode' after doing some setup."
  768. :type 'file
  769. :group 'SQL)
  770. (defcustom sql-solid-login-params '(user password server)
  771. "List of login parameters needed to connect to Solid."
  772. :type 'sql-login-params
  773. :version "24.1"
  774. :group 'SQL)
  775. ;; Customization for Sybase
  776. (defcustom sql-sybase-program "isql"
  777. "Command to start isql by Sybase.
  778. Starts `sql-interactive-mode' after doing some setup."
  779. :type 'file
  780. :group 'SQL)
  781. (defcustom sql-sybase-options nil
  782. "List of additional options for `sql-sybase-program'.
  783. Some versions of isql might require the -n option in order to work."
  784. :type '(repeat string)
  785. :version "20.8"
  786. :group 'SQL)
  787. (defcustom sql-sybase-login-params '(server user password database)
  788. "List of login parameters needed to connect to Sybase."
  789. :type 'sql-login-params
  790. :version "24.1"
  791. :group 'SQL)
  792. ;; Customization for Informix
  793. (defcustom sql-informix-program "dbaccess"
  794. "Command to start dbaccess by Informix.
  795. Starts `sql-interactive-mode' after doing some setup."
  796. :type 'file
  797. :group 'SQL)
  798. (defcustom sql-informix-login-params '(database)
  799. "List of login parameters needed to connect to Informix."
  800. :type 'sql-login-params
  801. :version "24.1"
  802. :group 'SQL)
  803. ;; Customization for Ingres
  804. (defcustom sql-ingres-program "sql"
  805. "Command to start sql by Ingres.
  806. Starts `sql-interactive-mode' after doing some setup."
  807. :type 'file
  808. :group 'SQL)
  809. (defcustom sql-ingres-login-params '(database)
  810. "List of login parameters needed to connect to Ingres."
  811. :type 'sql-login-params
  812. :version "24.1"
  813. :group 'SQL)
  814. ;; Customization for Microsoft
  815. (defcustom sql-ms-program "osql"
  816. "Command to start osql by Microsoft.
  817. Starts `sql-interactive-mode' after doing some setup."
  818. :type 'file
  819. :group 'SQL)
  820. (defcustom sql-ms-options '("-w" "300" "-n")
  821. ;; -w is the linesize
  822. "List of additional options for `sql-ms-program'."
  823. :type '(repeat string)
  824. :version "22.1"
  825. :group 'SQL)
  826. (defcustom sql-ms-login-params '(user password server database)
  827. "List of login parameters needed to connect to Microsoft."
  828. :type 'sql-login-params
  829. :version "24.1"
  830. :group 'SQL)
  831. ;; Customization for Postgres
  832. (defcustom sql-postgres-program "psql"
  833. "Command to start psql by Postgres.
  834. Starts `sql-interactive-mode' after doing some setup."
  835. :type 'file
  836. :group 'SQL)
  837. (defcustom sql-postgres-options '("-P" "pager=off")
  838. "List of additional options for `sql-postgres-program'.
  839. The default setting includes the -P option which breaks older versions
  840. of the psql client (such as version 6.5.3). The -P option is equivalent
  841. to the --pset option. If you want the psql to prompt you for a user
  842. name, add the string \"-u\" to the list of options. If you want to
  843. provide a user name on the command line (newer versions such as 7.1),
  844. add your name with a \"-U\" prefix (such as \"-Umark\") to the list."
  845. :type '(repeat string)
  846. :version "20.8"
  847. :group 'SQL)
  848. (defcustom sql-postgres-login-params `((user :default ,(user-login-name))
  849. (database :default ,(user-login-name))
  850. server)
  851. "List of login parameters needed to connect to Postgres."
  852. :type 'sql-login-params
  853. :version "24.1"
  854. :group 'SQL)
  855. ;; Customization for Interbase
  856. (defcustom sql-interbase-program "isql"
  857. "Command to start isql by Interbase.
  858. Starts `sql-interactive-mode' after doing some setup."
  859. :type 'file
  860. :group 'SQL)
  861. (defcustom sql-interbase-options nil
  862. "List of additional options for `sql-interbase-program'."
  863. :type '(repeat string)
  864. :version "20.8"
  865. :group 'SQL)
  866. (defcustom sql-interbase-login-params '(user password database)
  867. "List of login parameters needed to connect to Interbase."
  868. :type 'sql-login-params
  869. :version "24.1"
  870. :group 'SQL)
  871. ;; Customization for DB2
  872. (defcustom sql-db2-program "db2"
  873. "Command to start db2 by IBM.
  874. Starts `sql-interactive-mode' after doing some setup."
  875. :type 'file
  876. :group 'SQL)
  877. (defcustom sql-db2-options nil
  878. "List of additional options for `sql-db2-program'."
  879. :type '(repeat string)
  880. :version "20.8"
  881. :group 'SQL)
  882. (defcustom sql-db2-login-params nil
  883. "List of login parameters needed to connect to DB2."
  884. :type 'sql-login-params
  885. :version "24.1"
  886. :group 'SQL)
  887. ;; Customization for Linter
  888. (defcustom sql-linter-program "inl"
  889. "Command to start inl by RELEX.
  890. Starts `sql-interactive-mode' after doing some setup."
  891. :type 'file
  892. :group 'SQL)
  893. (defcustom sql-linter-options nil
  894. "List of additional options for `sql-linter-program'."
  895. :type '(repeat string)
  896. :version "21.3"
  897. :group 'SQL)
  898. (defcustom sql-linter-login-params '(user password database server)
  899. "Login parameters to needed to connect to Linter."
  900. :type 'sql-login-params
  901. :version "24.1"
  902. :group 'SQL)
  903. ;;; Variables which do not need customization
  904. (defvar sql-user-history nil
  905. "History of usernames used.")
  906. (defvar sql-database-history nil
  907. "History of databases used.")
  908. (defvar sql-server-history nil
  909. "History of servers used.")
  910. ;; Passwords are not kept in a history.
  911. (defvar sql-product-history nil
  912. "History of products used.")
  913. (defvar sql-connection-history nil
  914. "History of connections used.")
  915. (defvar sql-buffer nil
  916. "Current SQLi buffer.
  917. The global value of `sql-buffer' is the name of the latest SQLi buffer
  918. created. Any SQL buffer created will make a local copy of this value.
  919. See `sql-interactive-mode' for more on multiple sessions. If you want
  920. to change the SQLi buffer a SQL mode sends its SQL strings to, change
  921. the local value of `sql-buffer' using \\[sql-set-sqli-buffer].")
  922. (defvar sql-prompt-regexp nil
  923. "Prompt used to initialize `comint-prompt-regexp'.
  924. You can change `sql-prompt-regexp' on `sql-interactive-mode-hook'.")
  925. (defvar sql-prompt-length 0
  926. "Prompt used to set `left-margin' in `sql-interactive-mode'.
  927. You can change `sql-prompt-length' on `sql-interactive-mode-hook'.")
  928. (defvar sql-prompt-cont-regexp nil
  929. "Prompt pattern of statement continuation prompts.")
  930. (defvar sql-alternate-buffer-name nil
  931. "Buffer-local string used to possibly rename the SQLi buffer.
  932. Used by `sql-rename-buffer'.")
  933. (defun sql-buffer-live-p (buffer &optional product connection)
  934. "Returns non-nil if the process associated with buffer is live.
  935. BUFFER can be a buffer object or a buffer name. The buffer must
  936. be a live buffer, have an running process attached to it, be in
  937. `sql-interactive-mode', and, if PRODUCT or CONNECTION are
  938. specified, it's `sql-product' or `sql-connection' must match."
  939. (when buffer
  940. (setq buffer (get-buffer buffer))
  941. (and buffer
  942. (buffer-live-p buffer)
  943. (get-buffer-process buffer)
  944. (comint-check-proc buffer)
  945. (with-current-buffer buffer
  946. (and (derived-mode-p 'sql-interactive-mode)
  947. (or (not product)
  948. (eq product sql-product))
  949. (or (not connection)
  950. (eq connection sql-connection)))))))
  951. ;; Keymap for sql-interactive-mode.
  952. (defvar sql-interactive-mode-map
  953. (let ((map (make-sparse-keymap)))
  954. (if (fboundp 'set-keymap-parent)
  955. (set-keymap-parent map comint-mode-map); Emacs
  956. (if (fboundp 'set-keymap-parents)
  957. (set-keymap-parents map (list comint-mode-map)))); XEmacs
  958. (if (fboundp 'set-keymap-name)
  959. (set-keymap-name map 'sql-interactive-mode-map)); XEmacs
  960. (define-key map (kbd "C-j") 'sql-accumulate-and-indent)
  961. (define-key map (kbd "C-c C-w") 'sql-copy-column)
  962. (define-key map (kbd "O") 'sql-magic-go)
  963. (define-key map (kbd "o") 'sql-magic-go)
  964. (define-key map (kbd ";") 'sql-magic-semicolon)
  965. (define-key map (kbd "C-c C-l a") 'sql-list-all)
  966. (define-key map (kbd "C-c C-l t") 'sql-list-table)
  967. map)
  968. "Mode map used for `sql-interactive-mode'.
  969. Based on `comint-mode-map'.")
  970. ;; Keymap for sql-mode.
  971. (defvar sql-mode-map
  972. (let ((map (make-sparse-keymap)))
  973. (define-key map (kbd "C-c C-c") 'sql-send-paragraph)
  974. (define-key map (kbd "C-c C-r") 'sql-send-region)
  975. (define-key map (kbd "C-c C-s") 'sql-send-string)
  976. (define-key map (kbd "C-c C-b") 'sql-send-buffer)
  977. (define-key map (kbd "C-c C-i") 'sql-product-interactive)
  978. (define-key map (kbd "C-c C-l a") 'sql-list-all)
  979. (define-key map (kbd "C-c C-l t") 'sql-list-table)
  980. (define-key map [remap beginning-of-defun] 'sql-beginning-of-statement)
  981. (define-key map [remap end-of-defun] 'sql-end-of-statement)
  982. map)
  983. "Mode map used for `sql-mode'.")
  984. ;; easy menu for sql-mode.
  985. (easy-menu-define
  986. sql-mode-menu sql-mode-map
  987. "Menu for `sql-mode'."
  988. `("SQL"
  989. ["Send Paragraph" sql-send-paragraph (sql-buffer-live-p sql-buffer)]
  990. ["Send Region" sql-send-region (and mark-active
  991. (sql-buffer-live-p sql-buffer))]
  992. ["Send Buffer" sql-send-buffer (sql-buffer-live-p sql-buffer)]
  993. ["Send String" sql-send-string (sql-buffer-live-p sql-buffer)]
  994. "--"
  995. ["List all objects" sql-list-all (and (sql-buffer-live-p sql-buffer)
  996. (sql-get-product-feature sql-product :list-all))]
  997. ["List table details" sql-list-table (and (sql-buffer-live-p sql-buffer)
  998. (sql-get-product-feature sql-product :list-table))]
  999. "--"
  1000. ["Start SQLi session" sql-product-interactive
  1001. :visible (not sql-connection-alist)
  1002. :enable (sql-get-product-feature sql-product :sqli-comint-func)]
  1003. ("Start..."
  1004. :visible sql-connection-alist
  1005. :filter sql-connection-menu-filter
  1006. "--"
  1007. ["New SQLi Session" sql-product-interactive (sql-get-product-feature sql-product :sqli-comint-func)])
  1008. ["--"
  1009. :visible sql-connection-alist]
  1010. ["Show SQLi buffer" sql-show-sqli-buffer t]
  1011. ["Set SQLi buffer" sql-set-sqli-buffer t]
  1012. ["Pop to SQLi buffer after send"
  1013. sql-toggle-pop-to-buffer-after-send-region
  1014. :style toggle
  1015. :selected sql-pop-to-buffer-after-send-region]
  1016. ["--" nil nil]
  1017. ("Product"
  1018. ,@(mapcar (lambda (prod-info)
  1019. (let* ((prod (pop prod-info))
  1020. (name (or (plist-get prod-info :name)
  1021. (capitalize (symbol-name prod))))
  1022. (cmd (intern (format "sql-highlight-%s-keywords" prod))))
  1023. (fset cmd `(lambda () ,(format "Highlight %s SQL keywords." name)
  1024. (interactive)
  1025. (sql-set-product ',prod)))
  1026. (vector name cmd
  1027. :style 'radio
  1028. :selected `(eq sql-product ',prod))))
  1029. sql-product-alist))))
  1030. ;; easy menu for sql-interactive-mode.
  1031. (easy-menu-define
  1032. sql-interactive-mode-menu sql-interactive-mode-map
  1033. "Menu for `sql-interactive-mode'."
  1034. '("SQL"
  1035. ["Rename Buffer" sql-rename-buffer t]
  1036. ["Save Connection" sql-save-connection (not sql-connection)]
  1037. "--"
  1038. ["List all objects" sql-list-all (sql-get-product-feature sql-product :list-all)]
  1039. ["List table details" sql-list-table (sql-get-product-feature sql-product :list-table)]))
  1040. ;; Abbreviations -- if you want more of them, define them in your
  1041. ;; ~/.emacs file. Abbrevs have to be enabled in your ~/.emacs, too.
  1042. (defvar sql-mode-abbrev-table nil
  1043. "Abbrev table used in `sql-mode' and `sql-interactive-mode'.")
  1044. (unless sql-mode-abbrev-table
  1045. (define-abbrev-table 'sql-mode-abbrev-table nil))
  1046. (mapc
  1047. ;; In Emacs 22+, provide SYSTEM-FLAG to define-abbrev.
  1048. (lambda (abbrev)
  1049. (let ((name (car abbrev))
  1050. (expansion (cdr abbrev)))
  1051. (condition-case nil
  1052. (define-abbrev sql-mode-abbrev-table name expansion nil 0 t)
  1053. (error
  1054. (define-abbrev sql-mode-abbrev-table name expansion)))))
  1055. '(("ins" . "insert")
  1056. ("upd" . "update")
  1057. ("del" . "delete")
  1058. ("sel" . "select")
  1059. ("proc" . "procedure")
  1060. ("func" . "function")
  1061. ("cr" . "create")))
  1062. ;; Syntax Table
  1063. (defvar sql-mode-syntax-table
  1064. (let ((table (make-syntax-table)))
  1065. ;; C-style comments /**/ (see elisp manual "Syntax Flags"))
  1066. (modify-syntax-entry ?/ ". 14" table)
  1067. (modify-syntax-entry ?* ". 23" table)
  1068. ;; double-dash starts comments
  1069. (modify-syntax-entry ?- ". 12b" table)
  1070. ;; newline and formfeed end comments
  1071. (modify-syntax-entry ?\n "> b" table)
  1072. (modify-syntax-entry ?\f "> b" table)
  1073. ;; single quotes (') delimit strings
  1074. (modify-syntax-entry ?' "\"" table)
  1075. ;; double quotes (") don't delimit strings
  1076. (modify-syntax-entry ?\" "." table)
  1077. ;; Make these all punctuation
  1078. (mapc (lambda (c) (modify-syntax-entry c "." table))
  1079. (string-to-list "!#$%&+,.:;<=>?@\\|"))
  1080. table)
  1081. "Syntax table used in `sql-mode' and `sql-interactive-mode'.")
  1082. ;; Font lock support
  1083. (defvar sql-mode-font-lock-object-name
  1084. (eval-when-compile
  1085. (list (concat "^\\s-*\\(?:create\\|drop\\|alter\\)\\s-+" ;; lead off with CREATE, DROP or ALTER
  1086. "\\(?:\\w+\\s-+\\)*" ;; optional intervening keywords
  1087. "\\(?:table\\|view\\|\\(?:package\\|type\\)\\(?:\\s-+body\\)?\\|proc\\(?:edure\\)?"
  1088. "\\|function\\|trigger\\|sequence\\|rule\\|default\\)\\s-+"
  1089. "\\(\\w+\\)")
  1090. 1 'font-lock-function-name-face))
  1091. "Pattern to match the names of top-level objects.
  1092. The pattern matches the name in a CREATE, DROP or ALTER
  1093. statement. The format of variable should be a valid
  1094. `font-lock-keywords' entry.")
  1095. ;; While there are international and American standards for SQL, they
  1096. ;; are not followed closely, and most vendors offer significant
  1097. ;; capabilities beyond those defined in the standard specifications.
  1098. ;; SQL mode provides support for highlighting based on the product. In
  1099. ;; addition to highlighting the product keywords, any ANSI keywords not
  1100. ;; used by the product are also highlighted. This will help identify
  1101. ;; keywords that could be restricted in future versions of the product
  1102. ;; or might be a problem if ported to another product.
  1103. ;; To reduce the complexity and size of the regular expressions
  1104. ;; generated to match keywords, ANSI keywords are filtered out of
  1105. ;; product keywords if they are equivalent. To do this, we define a
  1106. ;; function `sql-font-lock-keywords-builder' that removes any keywords
  1107. ;; that are matched by the ANSI patterns and results in the same face
  1108. ;; being applied. For this to work properly, we must play some games
  1109. ;; with the execution and compile time behavior. This code is a
  1110. ;; little tricky but works properly.
  1111. ;; When defining the keywords for individual products you should
  1112. ;; include all of the keywords that you want matched. The filtering
  1113. ;; against the ANSI keywords will be automatic if you use the
  1114. ;; `sql-font-lock-keywords-builder' function and follow the
  1115. ;; implementation pattern used for the other products in this file.
  1116. (eval-when-compile
  1117. (defvar sql-mode-ansi-font-lock-keywords)
  1118. (setq sql-mode-ansi-font-lock-keywords nil))
  1119. (eval-and-compile
  1120. (defun sql-font-lock-keywords-builder (face boundaries &rest keywords)
  1121. "Generation of regexp matching any one of KEYWORDS."
  1122. (let ((bdy (or boundaries '("\\b" . "\\b")))
  1123. kwd)
  1124. ;; Remove keywords that are defined in ANSI
  1125. (setq kwd keywords)
  1126. ;; (dolist (k keywords)
  1127. ;; (catch 'next
  1128. ;; (dolist (a sql-mode-ansi-font-lock-keywords)
  1129. ;; (when (and (eq face (cdr a))
  1130. ;; (eq (string-match (car a) k 0) 0)
  1131. ;; (eq (match-end 0) (length k)))
  1132. ;; (setq kwd (delq k kwd))
  1133. ;; (throw 'next nil)))))
  1134. ;; Create a properly formed font-lock-keywords item
  1135. (cons (concat (car bdy)
  1136. (regexp-opt kwd t)
  1137. (cdr bdy))
  1138. face)))
  1139. (defun sql-regexp-abbrev (keyword)
  1140. (let ((brk (string-match "[~]" keyword))
  1141. (len (length keyword))
  1142. (sep "\\(?:")
  1143. re i)
  1144. (if (not brk)
  1145. keyword
  1146. (setq re (substring keyword 0 brk)
  1147. i (+ 2 brk)
  1148. brk (1+ brk))
  1149. (while (<= i len)
  1150. (setq re (concat re sep (substring keyword brk i))
  1151. sep "\\|"
  1152. i (1+ i)))
  1153. (concat re "\\)?"))))
  1154. (defun sql-regexp-abbrev-list (&rest keyw-list)
  1155. (let ((re nil)
  1156. (sep "\\<\\(?:"))
  1157. (while keyw-list
  1158. (setq re (concat re sep (sql-regexp-abbrev (car keyw-list)))
  1159. sep "\\|"
  1160. keyw-list (cdr keyw-list)))
  1161. (concat re "\\)\\>"))))
  1162. (eval-when-compile
  1163. (setq sql-mode-ansi-font-lock-keywords
  1164. (list
  1165. ;; ANSI Non Reserved keywords
  1166. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1167. "ada" "asensitive" "assignment" "asymmetric" "atomic" "between"
  1168. "bitvar" "called" "catalog_name" "chain" "character_set_catalog"
  1169. "character_set_name" "character_set_schema" "checked" "class_origin"
  1170. "cobol" "collation_catalog" "collation_name" "collation_schema"
  1171. "column_name" "command_function" "command_function_code" "committed"
  1172. "condition_number" "connection_name" "constraint_catalog"
  1173. "constraint_name" "constraint_schema" "contains" "cursor_name"
  1174. "datetime_interval_code" "datetime_interval_precision" "defined"
  1175. "definer" "dispatch" "dynamic_function" "dynamic_function_code"
  1176. "existing" "exists" "final" "fortran" "generated" "granted"
  1177. "hierarchy" "hold" "implementation" "infix" "insensitive" "instance"
  1178. "instantiable" "invoker" "key_member" "key_type" "length" "m"
  1179. "message_length" "message_octet_length" "message_text" "method" "more"
  1180. "mumps" "name" "nullable" "number" "options" "overlaps" "overriding"
  1181. "parameter_mode" "parameter_name" "parameter_ordinal_position"
  1182. "parameter_specific_catalog" "parameter_specific_name"
  1183. "parameter_specific_schema" "pascal" "pli" "position" "repeatable"
  1184. "returned_length" "returned_octet_length" "returned_sqlstate"
  1185. "routine_catalog" "routine_name" "routine_schema" "row_count" "scale"
  1186. "schema_name" "security" "self" "sensitive" "serializable"
  1187. "server_name" "similar" "simple" "source" "specific_name" "style"
  1188. "subclass_origin" "sublist" "symmetric" "system" "table_name"
  1189. "transaction_active" "transactions_committed"
  1190. "transactions_rolled_back" "transform" "transforms" "trigger_catalog"
  1191. "trigger_name" "trigger_schema" "type" "uncommitted" "unnamed"
  1192. "user_defined_type_catalog" "user_defined_type_name"
  1193. "user_defined_type_schema"
  1194. )
  1195. ;; ANSI Reserved keywords
  1196. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1197. "absolute" "action" "add" "admin" "after" "aggregate" "alias" "all"
  1198. "allocate" "alter" "and" "any" "are" "as" "asc" "assertion" "at"
  1199. "authorization" "before" "begin" "both" "breadth" "by" "call"
  1200. "cascade" "cascaded" "case" "catalog" "check" "class" "close"
  1201. "collate" "collation" "column" "commit" "completion" "connect"
  1202. "connection" "constraint" "constraints" "constructor" "continue"
  1203. "corresponding" "create" "cross" "cube" "current" "cursor" "cycle"
  1204. "data" "day" "deallocate" "declare" "default" "deferrable" "deferred"
  1205. "delete" "depth" "deref" "desc" "describe" "descriptor" "destroy"
  1206. "destructor" "deterministic" "diagnostics" "dictionary" "disconnect"
  1207. "distinct" "domain" "drop" "dynamic" "each" "else" "end" "equals"
  1208. "escape" "every" "except" "exception" "exec" "execute" "external"
  1209. "false" "fetch" "first" "for" "foreign" "found" "free" "from" "full"
  1210. "function" "general" "get" "global" "go" "goto" "grant" "group"
  1211. "grouping" "having" "host" "hour" "identity" "ignore" "immediate" "in"
  1212. "indicator" "initialize" "initially" "inner" "inout" "input" "insert"
  1213. "intersect" "into" "is" "isolation" "iterate" "join" "key" "language"
  1214. "last" "lateral" "leading" "left" "less" "level" "like" "limit"
  1215. "local" "locator" "map" "match" "minute" "modifies" "modify" "module"
  1216. "month" "names" "natural" "new" "next" "no" "none" "not" "null" "of"
  1217. "off" "old" "on" "only" "open" "operation" "option" "or" "order"
  1218. "ordinality" "out" "outer" "output" "pad" "parameter" "parameters"
  1219. "partial" "path" "postfix" "prefix" "preorder" "prepare" "preserve"
  1220. "primary" "prior" "privileges" "procedure" "public" "read" "reads"
  1221. "recursive" "references" "referencing" "relative" "restrict" "result"
  1222. "return" "returns" "revoke" "right" "role" "rollback" "rollup"
  1223. "routine" "rows" "savepoint" "schema" "scroll" "search" "second"
  1224. "section" "select" "sequence" "session" "set" "sets" "size" "some"
  1225. "space" "specific" "specifictype" "sql" "sqlexception" "sqlstate"
  1226. "sqlwarning" "start" "state" "statement" "static" "structure" "table"
  1227. "temporary" "terminate" "than" "then" "timezone_hour"
  1228. "timezone_minute" "to" "trailing" "transaction" "translation"
  1229. "trigger" "true" "under" "union" "unique" "unknown" "unnest" "update"
  1230. "usage" "using" "value" "values" "variable" "view" "when" "whenever"
  1231. "where" "with" "without" "work" "write" "year"
  1232. )
  1233. ;; ANSI Functions
  1234. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1235. "abs" "avg" "bit_length" "cardinality" "cast" "char_length"
  1236. "character_length" "coalesce" "convert" "count" "current_date"
  1237. "current_path" "current_role" "current_time" "current_timestamp"
  1238. "current_user" "extract" "localtime" "localtimestamp" "lower" "max"
  1239. "min" "mod" "nullif" "octet_length" "overlay" "placing" "session_user"
  1240. "substring" "sum" "system_user" "translate" "treat" "trim" "upper"
  1241. "user"
  1242. )
  1243. ;; ANSI Data Types
  1244. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1245. "array" "binary" "bit" "blob" "boolean" "char" "character" "clob"
  1246. "date" "dec" "decimal" "double" "float" "int" "integer" "interval"
  1247. "large" "national" "nchar" "nclob" "numeric" "object" "precision"
  1248. "real" "ref" "row" "scope" "smallint" "time" "timestamp" "varchar"
  1249. "varying" "zone"
  1250. ))))
  1251. (defvar sql-mode-ansi-font-lock-keywords
  1252. (eval-when-compile sql-mode-ansi-font-lock-keywords)
  1253. "ANSI SQL keywords used by font-lock.
  1254. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1255. regular expressions are created during compilation by calling the
  1256. function `regexp-opt'. Therefore, take a look at the source before
  1257. you define your own `sql-mode-ansi-font-lock-keywords'. You may want
  1258. to add functions and PL/SQL keywords.")
  1259. (defun sql-oracle-show-reserved-words ()
  1260. ;; This function is for use by the maintainer of SQL.EL only.
  1261. (interactive)
  1262. (if (or (and (not (derived-mode-p 'sql-mode))
  1263. (not (derived-mode-p 'sql-interactive-mode)))
  1264. (not sql-buffer)
  1265. (not (eq sql-product 'oracle)))
  1266. (error "Not an Oracle buffer")
  1267. (let ((b "*RESERVED WORDS*"))
  1268. (sql-execute sql-buffer b
  1269. (concat "SELECT "
  1270. " keyword "
  1271. ", reserved AS \"Res\" "
  1272. ", res_type AS \"Type\" "
  1273. ", res_attr AS \"Attr\" "
  1274. ", res_semi AS \"Semi\" "
  1275. ", duplicate AS \"Dup\" "
  1276. "FROM V$RESERVED_WORDS "
  1277. "WHERE length > 1 "
  1278. "AND SUBSTR(keyword, 1, 1) BETWEEN 'A' AND 'Z' "
  1279. "ORDER BY 2 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC, 1;")
  1280. nil nil)
  1281. (with-current-buffer b
  1282. (set (make-local-variable 'sql-product) 'oracle)
  1283. (sql-product-font-lock t nil)
  1284. (font-lock-mode +1)))))
  1285. (defvar sql-mode-oracle-font-lock-keywords
  1286. (eval-when-compile
  1287. (list
  1288. ;; Oracle SQL*Plus Commands
  1289. ;; Only recognized in they start in column 1 and the
  1290. ;; abbreviation is followed by a space or the end of line.
  1291. "\\|"
  1292. (list (concat "^" (sql-regexp-abbrev "rem~ark") "\\(?:\\s-.*\\)?$")
  1293. 0 'font-lock-comment-face t)
  1294. (list
  1295. (concat
  1296. "^\\(?:"
  1297. (sql-regexp-abbrev-list
  1298. "[@]\\{1,2\\}" "acc~ept" "a~ppend" "archive" "attribute"
  1299. "bre~ak" "bti~tle" "c~hange" "cl~ear" "col~umn" "conn~ect"
  1300. "copy" "def~ine" "del" "desc~ribe" "disc~onnect" "ed~it"
  1301. "exec~ute" "exit" "get" "help" "ho~st" "[$]" "i~nput" "l~ist"
  1302. "passw~ord" "pau~se" "pri~nt" "pro~mpt" "quit" "recover"
  1303. "repf~ooter" "reph~eader" "r~un" "sav~e" "sho~w" "shutdown"
  1304. "spo~ol" "sta~rt" "startup" "store" "tim~ing" "tti~tle"
  1305. "undef~ine" "var~iable" "whenever")
  1306. "\\|"
  1307. (concat "\\(?:"
  1308. (sql-regexp-abbrev "comp~ute")
  1309. "\\s-+"
  1310. (sql-regexp-abbrev-list
  1311. "avg" "cou~nt" "min~imum" "max~imum" "num~ber" "sum"
  1312. "std" "var~iance")
  1313. "\\)")
  1314. "\\|"
  1315. (concat "\\(?:set\\s-+"
  1316. (sql-regexp-abbrev-list
  1317. "appi~nfo" "array~size" "auto~commit" "autop~rint"
  1318. "autorecovery" "autot~race" "blo~ckterminator"
  1319. "cmds~ep" "colsep" "com~patibility" "con~cat"
  1320. "copyc~ommit" "copytypecheck" "def~ine" "describe"
  1321. "echo" "editf~ile" "emb~edded" "esc~ape" "feed~back"
  1322. "flagger" "flu~sh" "hea~ding" "heads~ep" "instance"
  1323. "lin~esize" "lobof~fset" "long" "longc~hunksize"
  1324. "mark~up" "newp~age" "null" "numf~ormat" "num~width"
  1325. "pages~ize" "pau~se" "recsep" "recsepchar"
  1326. "scan" "serverout~put" "shift~inout" "show~mode"
  1327. "sqlbl~anklines" "sqlc~ase" "sqlco~ntinue"
  1328. "sqln~umber" "sqlpluscompat~ibility" "sqlpre~fix"
  1329. "sqlp~rompt" "sqlt~erminator" "suf~fix" "tab"
  1330. "term~out" "ti~me" "timi~ng" "trim~out" "trims~pool"
  1331. "und~erline" "ver~ify" "wra~p")
  1332. "\\)")
  1333. "\\)\\(?:\\s-.*\\)?\\(?:[-]\n.*\\)*$")
  1334. 0 'font-lock-doc-face t)
  1335. ;; Oracle Functions
  1336. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1337. "abs" "acos" "add_months" "appendchildxml" "ascii" "asciistr" "asin"
  1338. "atan" "atan2" "avg" "bfilename" "bin_to_num" "bitand" "cardinality"
  1339. "cast" "ceil" "chartorowid" "chr" "cluster_id" "cluster_probability"
  1340. "cluster_set" "coalesce" "collect" "compose" "concat" "convert" "corr"
  1341. "connect_by_root" "connect_by_iscycle" "connect_by_isleaf"
  1342. "corr_k" "corr_s" "cos" "cosh" "count" "covar_pop" "covar_samp"
  1343. "cube_table" "cume_dist" "current_date" "current_timestamp" "cv"
  1344. "dataobj_to_partition" "dbtimezone" "decode" "decompose" "deletexml"
  1345. "dense_rank" "depth" "deref" "dump" "empty_blob" "empty_clob"
  1346. "existsnode" "exp" "extract" "extractvalue" "feature_id" "feature_set"
  1347. "feature_value" "first" "first_value" "floor" "from_tz" "greatest"
  1348. "grouping" "grouping_id" "group_id" "hextoraw" "initcap"
  1349. "insertchildxml" "insertchildxmlafter" "insertchildxmlbefore"
  1350. "insertxmlafter" "insertxmlbefore" "instr" "instr2" "instr4" "instrb"
  1351. "instrc" "iteration_number" "lag" "last" "last_day" "last_value"
  1352. "lead" "least" "length" "length2" "length4" "lengthb" "lengthc"
  1353. "listagg" "ln" "lnnvl" "localtimestamp" "log" "lower" "lpad" "ltrim"
  1354. "make_ref" "max" "median" "min" "mod" "months_between" "nanvl" "nchr"
  1355. "new_time" "next_day" "nlssort" "nls_charset_decl_len"
  1356. "nls_charset_id" "nls_charset_name" "nls_initcap" "nls_lower"
  1357. "nls_upper" "nth_value" "ntile" "nullif" "numtodsinterval"
  1358. "numtoyminterval" "nvl" "nvl2" "ora_dst_affected" "ora_dst_convert"
  1359. "ora_dst_error" "ora_hash" "path" "percentile_cont" "percentile_disc"
  1360. "percent_rank" "power" "powermultiset" "powermultiset_by_cardinality"
  1361. "prediction" "prediction_bounds" "prediction_cost"
  1362. "prediction_details" "prediction_probability" "prediction_set"
  1363. "presentnnv" "presentv" "previous" "rank" "ratio_to_report" "rawtohex"
  1364. "rawtonhex" "ref" "reftohex" "regexp_count" "regexp_instr"
  1365. "regexp_replace" "regexp_substr" "regr_avgx" "regr_avgy" "regr_count"
  1366. "regr_intercept" "regr_r2" "regr_slope" "regr_sxx" "regr_sxy"
  1367. "regr_syy" "remainder" "replace" "round" "rowidtochar" "rowidtonchar"
  1368. "row_number" "rpad" "rtrim" "scn_to_timestamp" "sessiontimezone" "set"
  1369. "sign" "sin" "sinh" "soundex" "sqrt" "stats_binomial_test"
  1370. "stats_crosstab" "stats_f_test" "stats_ks_test" "stats_mode"
  1371. "stats_mw_test" "stats_one_way_anova" "stats_t_test_indep"
  1372. "stats_t_test_indepu" "stats_t_test_one" "stats_t_test_paired"
  1373. "stats_wsr_test" "stddev" "stddev_pop" "stddev_samp" "substr"
  1374. "substr2" "substr4" "substrb" "substrc" "sum" "sysdate" "systimestamp"
  1375. "sys_connect_by_path" "sys_context" "sys_dburigen" "sys_extract_utc"
  1376. "sys_guid" "sys_typeid" "sys_xmlagg" "sys_xmlgen" "tan" "tanh"
  1377. "timestamp_to_scn" "to_binary_double" "to_binary_float" "to_blob"
  1378. "to_char" "to_clob" "to_date" "to_dsinterval" "to_lob" "to_multi_byte"
  1379. "to_nchar" "to_nclob" "to_number" "to_single_byte" "to_timestamp"
  1380. "to_timestamp_tz" "to_yminterval" "translate" "treat" "trim" "trunc"
  1381. "tz_offset" "uid" "unistr" "updatexml" "upper" "user" "userenv"
  1382. "value" "variance" "var_pop" "var_samp" "vsize" "width_bucket"
  1383. "xmlagg" "xmlcast" "xmlcdata" "xmlcolattval" "xmlcomment" "xmlconcat"
  1384. "xmldiff" "xmlelement" "xmlexists" "xmlforest" "xmlisvalid" "xmlparse"
  1385. "xmlpatch" "xmlpi" "xmlquery" "xmlroot" "xmlsequence" "xmlserialize"
  1386. "xmltable" "xmltransform"
  1387. )
  1388. ;; See the table V$RESERVED_WORDS
  1389. ;; Oracle Keywords
  1390. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1391. "abort" "access" "accessed" "account" "activate" "add" "admin"
  1392. "advise" "after" "agent" "aggregate" "all" "allocate" "allow" "alter"
  1393. "always" "analyze" "ancillary" "and" "any" "apply" "archive"
  1394. "archivelog" "array" "as" "asc" "associate" "at" "attribute"
  1395. "attributes" "audit" "authenticated" "authid" "authorization" "auto"
  1396. "autoallocate" "automatic" "availability" "backup" "before" "begin"
  1397. "behalf" "between" "binding" "bitmap" "block" "blocksize" "body"
  1398. "both" "buffer_pool" "build" "by" "cache" "call" "cancel"
  1399. "cascade" "case" "category" "certificate" "chained" "change" "check"
  1400. "checkpoint" "child" "chunk" "class" "clear" "clone" "close" "cluster"
  1401. "column" "column_value" "columns" "comment" "commit" "committed"
  1402. "compatibility" "compile" "complete" "composite_limit" "compress"
  1403. "compute" "connect" "connect_time" "consider" "consistent"
  1404. "constraint" "constraints" "constructor" "contents" "context"
  1405. "continue" "controlfile" "corruption" "cost" "cpu_per_call"
  1406. "cpu_per_session" "create" "cross" "cube" "current" "currval" "cycle"
  1407. "dangling" "data" "database" "datafile" "datafiles" "day" "ddl"
  1408. "deallocate" "debug" "default" "deferrable" "deferred" "definer"
  1409. "delay" "delete" "demand" "desc" "determines" "deterministic"
  1410. "dictionary" "dimension" "directory" "disable" "disassociate"
  1411. "disconnect" "distinct" "distinguished" "distributed" "dml" "drop"
  1412. "each" "element" "else" "enable" "end" "equals_path" "escape"
  1413. "estimate" "except" "exceptions" "exchange" "excluding" "exists"
  1414. "expire" "explain" "extent" "external" "externally"
  1415. "failed_login_attempts" "fast" "file" "final" "finish" "flush" "for"
  1416. "force" "foreign" "freelist" "freelists" "freepools" "fresh" "from"
  1417. "full" "function" "functions" "generated" "global" "global_name"
  1418. "globally" "grant" "group" "grouping" "groups" "guard" "hash"
  1419. "hashkeys" "having" "heap" "hierarchy" "id" "identified" "identifier"
  1420. "idle_time" "immediate" "in" "including" "increment" "index" "indexed"
  1421. "indexes" "indextype" "indextypes" "indicator" "initial" "initialized"
  1422. "initially" "initrans" "inner" "insert" "instance" "instantiable"
  1423. "instead" "intersect" "into" "invalidate" "is" "isolation" "java"
  1424. "join" "keep" "key" "kill" "language" "left" "less" "level"
  1425. "levels" "library" "like" "like2" "like4" "likec" "limit" "link"
  1426. "list" "lob" "local" "location" "locator" "lock" "log" "logfile"
  1427. "logging" "logical" "logical_reads_per_call"
  1428. "logical_reads_per_session" "managed" "management" "manual" "map"
  1429. "mapping" "master" "matched" "materialized" "maxdatafiles"
  1430. "maxextents" "maximize" "maxinstances" "maxlogfiles" "maxloghistory"
  1431. "maxlogmembers" "maxsize" "maxtrans" "maxvalue" "member" "memory"
  1432. "merge" "migrate" "minextents" "minimize" "minimum" "minus" "minvalue"
  1433. "mode" "modify" "monitoring" "month" "mount" "move" "movement" "name"
  1434. "named" "natural" "nested" "never" "new" "next" "nextval" "no"
  1435. "noarchivelog" "noaudit" "nocache" "nocompress" "nocopy" "nocycle"
  1436. "nodelay" "noforce" "nologging" "nomapping" "nomaxvalue" "nominimize"
  1437. "nominvalue" "nomonitoring" "none" "noorder" "noparallel" "norely"
  1438. "noresetlogs" "noreverse" "normal" "norowdependencies" "nosort"
  1439. "noswitch" "not" "nothing" "notimeout" "novalidate" "nowait" "null"
  1440. "nulls" "object" "of" "off" "offline" "oidindex" "old" "on" "online"
  1441. "only" "open" "operator" "optimal" "option" "or" "order"
  1442. "organization" "out" "outer" "outline" "overflow" "overriding"
  1443. "package" "packages" "parallel" "parallel_enable" "parameters"
  1444. "parent" "partition" "partitions" "password" "password_grace_time"
  1445. "password_life_time" "password_lock_time" "password_reuse_max"
  1446. "password_reuse_time" "password_verify_function" "pctfree"
  1447. "pctincrease" "pctthreshold" "pctused" "pctversion" "percent"
  1448. "performance" "permanent" "pfile" "physical" "pipelined" "plan"
  1449. "post_transaction" "pragma" "prebuilt" "preserve" "primary" "private"
  1450. "private_sga" "privileges" "procedure" "profile" "protection" "public"
  1451. "purge" "query" "quiesce" "quota" "range" "read" "reads" "rebuild"
  1452. "records_per_block" "recover" "recovery" "recycle" "reduced" "ref"
  1453. "references" "referencing" "refresh" "register" "reject" "relational"
  1454. "rely" "rename" "reset" "resetlogs" "resize" "resolve" "resolver"
  1455. "resource" "restrict" "restrict_references" "restricted" "result"
  1456. "resumable" "resume" "retention" "return" "returning" "reuse"
  1457. "reverse" "revoke" "rewrite" "right" "rnds" "rnps" "role" "roles"
  1458. "rollback" "rollup" "row" "rowdependencies" "rownum" "rows" "sample"
  1459. "savepoint" "scan" "schema" "scn" "scope" "segment" "select"
  1460. "selectivity" "self" "sequence" "serializable" "session"
  1461. "sessions_per_user" "set" "sets" "settings" "shared" "shared_pool"
  1462. "shrink" "shutdown" "siblings" "sid" "single" "size" "skip" "some"
  1463. "sort" "source" "space" "specification" "spfile" "split" "standby"
  1464. "start" "statement_id" "static" "statistics" "stop" "storage" "store"
  1465. "structure" "subpartition" "subpartitions" "substitutable"
  1466. "successful" "supplemental" "suspend" "switch" "switchover" "synonym"
  1467. "sys" "system" "table" "tables" "tablespace" "tempfile" "template"
  1468. "temporary" "test" "than" "then" "thread" "through" "time_zone"
  1469. "timeout" "to" "trace" "transaction" "trigger" "triggers" "truncate"
  1470. "trust" "type" "types" "unarchived" "under" "under_path" "undo"
  1471. "uniform" "union" "unique" "unlimited" "unlock" "unquiesce"
  1472. "unrecoverable" "until" "unusable" "unused" "update" "upgrade" "usage"
  1473. "use" "using" "validate" "validation" "value" "values" "variable"
  1474. "varray" "version" "view" "wait" "when" "whenever" "where" "with"
  1475. "without" "wnds" "wnps" "work" "write" "xmldata" "xmlschema" "xmltype"
  1476. )
  1477. ;; Oracle Data Types
  1478. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1479. "bfile" "binary_double" "binary_float" "blob" "byte" "char" "charbyte"
  1480. "clob" "date" "day" "float" "interval" "local" "long" "longraw"
  1481. "minute" "month" "nchar" "nclob" "number" "nvarchar2" "raw" "rowid" "second"
  1482. "time" "timestamp" "urowid" "varchar2" "with" "year" "zone"
  1483. )
  1484. ;; Oracle PL/SQL Attributes
  1485. (sql-font-lock-keywords-builder 'font-lock-builtin-face '("%" . "\\b")
  1486. "bulk_exceptions" "bulk_rowcount" "found" "isopen" "notfound"
  1487. "rowcount" "rowtype" "type"
  1488. )
  1489. ;; Oracle PL/SQL Functions
  1490. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1491. "delete" "trim" "extend" "exists" "first" "last" "count" "limit"
  1492. "prior" "next"
  1493. )
  1494. ;; Oracle PL/SQL Reserved words
  1495. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1496. "all" "alter" "and" "any" "as" "asc" "at" "begin" "between" "by"
  1497. "case" "check" "clusters" "cluster" "colauth" "columns" "compress"
  1498. "connect" "crash" "create" "cursor" "declare" "default" "desc"
  1499. "distinct" "drop" "else" "end" "exception" "exclusive" "fetch" "for"
  1500. "from" "function" "goto" "grant" "group" "having" "identified" "if"
  1501. "in" "index" "indexes" "insert" "intersect" "into" "is" "like" "lock"
  1502. "minus" "mode" "nocompress" "not" "nowait" "null" "of" "on" "option"
  1503. "or" "order" "overlaps" "procedure" "public" "resource" "revoke"
  1504. "select" "share" "size" "sql" "start" "subtype" "tabauth" "table"
  1505. "then" "to" "type" "union" "unique" "update" "values" "view" "views"
  1506. "when" "where" "with"
  1507. "true" "false"
  1508. "raise_application_error"
  1509. )
  1510. ;; Oracle PL/SQL Keywords
  1511. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1512. "a" "add" "agent" "aggregate" "array" "attribute" "authid" "avg"
  1513. "bfile_base" "binary" "blob_base" "block" "body" "both" "bound" "bulk"
  1514. "byte" "c" "call" "calling" "cascade" "char" "char_base" "character"
  1515. "charset" "charsetform" "charsetid" "clob_base" "close" "collect"
  1516. "comment" "commit" "committed" "compiled" "constant" "constructor"
  1517. "context" "continue" "convert" "count" "current" "customdatum"
  1518. "dangling" "data" "date" "date_base" "day" "define" "delete"
  1519. "deterministic" "double" "duration" "element" "elsif" "empty" "escape"
  1520. "except" "exceptions" "execute" "exists" "exit" "external" "final"
  1521. "fixed" "float" "forall" "force" "general" "hash" "heap" "hidden"
  1522. "hour" "immediate" "including" "indicator" "indices" "infinite"
  1523. "instantiable" "int" "interface" "interval" "invalidate" "isolation"
  1524. "java" "language" "large" "leading" "length" "level" "library" "like2"
  1525. "like4" "likec" "limit" "limited" "local" "long" "loop" "map" "max"
  1526. "maxlen" "member" "merge" "min" "minute" "mod" "modify" "month"
  1527. "multiset" "name" "nan" "national" "native" "nchar" "new" "nocopy"
  1528. "number_base" "object" "ocicoll" "ocidate" "ocidatetime" "ociduration"
  1529. "ociinterval" "ociloblocator" "ocinumber" "ociraw" "ociref"
  1530. "ocirefcursor" "ocirowid" "ocistring" "ocitype" "old" "only" "opaque"
  1531. "open" "operator" "oracle" "oradata" "organization" "orlany" "orlvary"
  1532. "others" "out" "overriding" "package" "parallel_enable" "parameter"
  1533. "parameters" "parent" "partition" "pascal" "pipe" "pipelined" "pragma"
  1534. "precision" "prior" "private" "raise" "range" "raw" "read" "record"
  1535. "ref" "reference" "relies_on" "rem" "remainder" "rename" "result"
  1536. "result_cache" "return" "returning" "reverse" "rollback" "row"
  1537. "sample" "save" "savepoint" "sb1" "sb2" "sb4" "second" "segment"
  1538. "self" "separate" "sequence" "serializable" "set" "short" "size_t"
  1539. "some" "sparse" "sqlcode" "sqldata" "sqlname" "sqlstate" "standard"
  1540. "static" "stddev" "stored" "string" "struct" "style" "submultiset"
  1541. "subpartition" "substitutable" "sum" "synonym" "tdo" "the" "time"
  1542. "timestamp" "timezone_abbr" "timezone_hour" "timezone_minute"
  1543. "timezone_region" "trailing" "transaction" "transactional" "trusted"
  1544. "ub1" "ub2" "ub4" "under" "unsigned" "untrusted" "use" "using"
  1545. "valist" "value" "variable" "variance" "varray" "varying" "void"
  1546. "while" "work" "wrapped" "write" "year" "zone"
  1547. ;; Pragma
  1548. "autonomous_transaction" "exception_init" "inline"
  1549. "restrict_references" "serially_reusable"
  1550. )
  1551. ;; Oracle PL/SQL Data Types
  1552. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1553. "\"BINARY LARGE OBJECT\"" "\"CHAR LARGE OBJECT\"" "\"CHAR VARYING\""
  1554. "\"CHARACTER LARGE OBJECT\"" "\"CHARACTER VARYING\""
  1555. "\"DOUBLE PRECISION\"" "\"INTERVAL DAY TO SECOND\""
  1556. "\"INTERVAL YEAR TO MONTH\"" "\"LONG RAW\"" "\"NATIONAL CHAR\""
  1557. "\"NATIONAL CHARACTER LARGE OBJECT\"" "\"NATIONAL CHARACTER\""
  1558. "\"NCHAR LARGE OBJECT\"" "\"NCHAR\"" "\"NCLOB\"" "\"NVARCHAR2\""
  1559. "\"TIME WITH TIME ZONE\"" "\"TIMESTAMP WITH LOCAL TIME ZONE\""
  1560. "\"TIMESTAMP WITH TIME ZONE\""
  1561. "bfile" "bfile_base" "binary_double" "binary_float" "binary_integer"
  1562. "blob" "blob_base" "boolean" "char" "character" "char_base" "clob"
  1563. "clob_base" "cursor" "date" "day" "dec" "decimal"
  1564. "dsinterval_unconstrained" "float" "int" "integer" "interval" "local"
  1565. "long" "mlslabel" "month" "natural" "naturaln" "nchar_cs" "number"
  1566. "number_base" "numeric" "pls_integer" "positive" "positiven" "raw"
  1567. "real" "ref" "rowid" "second" "signtype" "simple_double"
  1568. "simple_float" "simple_integer" "smallint" "string" "time" "timestamp"
  1569. "timestamp_ltz_unconstrained" "timestamp_tz_unconstrained"
  1570. "timestamp_unconstrained" "time_tz_unconstrained" "time_unconstrained"
  1571. "to" "urowid" "varchar" "varchar2" "with" "year"
  1572. "yminterval_unconstrained" "zone"
  1573. )
  1574. ;; Oracle PL/SQL Exceptions
  1575. (sql-font-lock-keywords-builder 'font-lock-warning-face nil
  1576. "access_into_null" "case_not_found" "collection_is_null"
  1577. "cursor_already_open" "dup_val_on_index" "invalid_cursor"
  1578. "invalid_number" "login_denied" "no_data_found" "no_data_needed"
  1579. "not_logged_on" "program_error" "rowtype_mismatch" "self_is_null"
  1580. "storage_error" "subscript_beyond_count" "subscript_outside_limit"
  1581. "sys_invalid_rowid" "timeout_on_resource" "too_many_rows"
  1582. "value_error" "zero_divide"
  1583. )))
  1584. "Oracle SQL keywords used by font-lock.
  1585. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1586. regular expressions are created during compilation by calling the
  1587. function `regexp-opt'. Therefore, take a look at the source before
  1588. you define your own `sql-mode-oracle-font-lock-keywords'. You may want
  1589. to add functions and PL/SQL keywords.")
  1590. (defvar sql-mode-postgres-font-lock-keywords
  1591. (eval-when-compile
  1592. (list
  1593. ;; Postgres psql commands
  1594. '("^\\s-*\\\\.*$" . font-lock-doc-face)
  1595. ;; Postgres unreserved words but may have meaning
  1596. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil "a"
  1597. "abs" "absent" "according" "ada" "alias" "allocate" "are" "array_agg"
  1598. "asensitive" "atomic" "attribute" "attributes" "avg" "base64"
  1599. "bernoulli" "bit_length" "bitvar" "blob" "blocked" "bom" "breadth" "c"
  1600. "call" "cardinality" "catalog_name" "ceil" "ceiling" "char_length"
  1601. "character_length" "character_set_catalog" "character_set_name"
  1602. "character_set_schema" "characters" "checked" "class_origin" "clob"
  1603. "cobol" "collation" "collation_catalog" "collation_name"
  1604. "collation_schema" "collect" "column_name" "columns"
  1605. "command_function" "command_function_code" "completion" "condition"
  1606. "condition_number" "connect" "connection_name" "constraint_catalog"
  1607. "constraint_name" "constraint_schema" "constructor" "contains"
  1608. "control" "convert" "corr" "corresponding" "count" "covar_pop"
  1609. "covar_samp" "cube" "cume_dist" "current_default_transform_group"
  1610. "current_path" "current_transform_group_for_type" "cursor_name"
  1611. "datalink" "datetime_interval_code" "datetime_interval_precision" "db"
  1612. "defined" "degree" "dense_rank" "depth" "deref" "derived" "describe"
  1613. "descriptor" "destroy" "destructor" "deterministic" "diagnostics"
  1614. "disconnect" "dispatch" "dlnewcopy" "dlpreviouscopy" "dlurlcomplete"
  1615. "dlurlcompleteonly" "dlurlcompletewrite" "dlurlpath" "dlurlpathonly"
  1616. "dlurlpathwrite" "dlurlscheme" "dlurlserver" "dlvalue" "dynamic"
  1617. "dynamic_function" "dynamic_function_code" "element" "empty"
  1618. "end-exec" "equals" "every" "exception" "exec" "existing" "exp" "file"
  1619. "filter" "final" "first_value" "flag" "floor" "fortran" "found" "free"
  1620. "fs" "fusion" "g" "general" "generated" "get" "go" "goto" "grouping"
  1621. "hex" "hierarchy" "host" "id" "ignore" "implementation" "import"
  1622. "indent" "indicator" "infix" "initialize" "instance" "instantiable"
  1623. "integrity" "intersection" "iterate" "k" "key_member" "key_type" "lag"
  1624. "last_value" "lateral" "lead" "length" "less" "library" "like_regex"
  1625. "link" "ln" "locator" "lower" "m" "map" "matched" "max"
  1626. "max_cardinality" "member" "merge" "message_length"
  1627. "message_octet_length" "message_text" "method" "min" "mod" "modifies"
  1628. "modify" "module" "more" "multiset" "mumps" "namespace" "nclob"
  1629. "nesting" "new" "nfc" "nfd" "nfkc" "nfkd" "nil" "normalize"
  1630. "normalized" "nth_value" "ntile" "nullable" "number"
  1631. "occurrences_regex" "octet_length" "octets" "old" "open" "operation"
  1632. "ordering" "ordinality" "others" "output" "overriding" "p" "pad"
  1633. "parameter" "parameter_mode" "parameter_name"
  1634. "parameter_ordinal_position" "parameter_specific_catalog"
  1635. "parameter_specific_name" "parameter_specific_schema" "parameters"
  1636. "pascal" "passing" "passthrough" "percent_rank" "percentile_cont"
  1637. "percentile_disc" "permission" "pli" "position_regex" "postfix"
  1638. "power" "prefix" "preorder" "public" "rank" "reads" "recovery" "ref"
  1639. "referencing" "regr_avgx" "regr_avgy" "regr_count" "regr_intercept"
  1640. "regr_r2" "regr_slope" "regr_sxx" "regr_sxy" "regr_syy" "requiring"
  1641. "respect" "restore" "result" "return" "returned_cardinality"
  1642. "returned_length" "returned_octet_length" "returned_sqlstate" "rollup"
  1643. "routine" "routine_catalog" "routine_name" "routine_schema"
  1644. "row_count" "row_number" "scale" "schema_name" "scope" "scope_catalog"
  1645. "scope_name" "scope_schema" "section" "selective" "self" "sensitive"
  1646. "server_name" "sets" "size" "source" "space" "specific"
  1647. "specific_name" "specifictype" "sql" "sqlcode" "sqlerror"
  1648. "sqlexception" "sqlstate" "sqlwarning" "sqrt" "state" "static"
  1649. "stddev_pop" "stddev_samp" "structure" "style" "subclass_origin"
  1650. "sublist" "submultiset" "substring_regex" "sum" "system_user" "t"
  1651. "table_name" "tablesample" "terminate" "than" "ties" "timezone_hour"
  1652. "timezone_minute" "token" "top_level_count" "transaction_active"
  1653. "transactions_committed" "transactions_rolled_back" "transform"
  1654. "transforms" "translate" "translate_regex" "translation"
  1655. "trigger_catalog" "trigger_name" "trigger_schema" "trim_array"
  1656. "uescape" "under" "unlink" "unnamed" "unnest" "untyped" "upper" "uri"
  1657. "usage" "user_defined_type_catalog" "user_defined_type_code"
  1658. "user_defined_type_name" "user_defined_type_schema" "var_pop"
  1659. "var_samp" "varbinary" "variable" "whenever" "width_bucket" "within"
  1660. "xmlagg" "xmlbinary" "xmlcast" "xmlcomment" "xmldeclaration"
  1661. "xmldocument" "xmlexists" "xmliterate" "xmlnamespaces" "xmlquery"
  1662. "xmlschema" "xmltable" "xmltext" "xmlvalidate"
  1663. )
  1664. ;; Postgres non-reserved words
  1665. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1666. "abort" "absolute" "access" "action" "add" "admin" "after" "aggregate"
  1667. "also" "alter" "always" "assertion" "assignment" "at" "backward"
  1668. "before" "begin" "between" "by" "cache" "called" "cascade" "cascaded"
  1669. "catalog" "chain" "characteristics" "checkpoint" "class" "close"
  1670. "cluster" "coalesce" "comment" "comments" "commit" "committed"
  1671. "configuration" "connection" "constraints" "content" "continue"
  1672. "conversion" "copy" "cost" "createdb" "createrole" "createuser" "csv"
  1673. "current" "cursor" "cycle" "data" "database" "day" "deallocate" "dec"
  1674. "declare" "defaults" "deferred" "definer" "delete" "delimiter"
  1675. "delimiters" "dictionary" "disable" "discard" "document" "domain"
  1676. "drop" "each" "enable" "encoding" "encrypted" "enum" "escape"
  1677. "exclude" "excluding" "exclusive" "execute" "exists" "explain"
  1678. "external" "extract" "family" "first" "float" "following" "force"
  1679. "forward" "function" "functions" "global" "granted" "greatest"
  1680. "handler" "header" "hold" "hour" "identity" "if" "immediate"
  1681. "immutable" "implicit" "including" "increment" "index" "indexes"
  1682. "inherit" "inherits" "inline" "inout" "input" "insensitive" "insert"
  1683. "instead" "invoker" "isolation" "key" "language" "large" "last"
  1684. "lc_collate" "lc_ctype" "least" "level" "listen" "load" "local"
  1685. "location" "lock" "login" "mapping" "match" "maxvalue" "minute"
  1686. "minvalue" "mode" "month" "move" "name" "names" "national" "nchar"
  1687. "next" "no" "nocreatedb" "nocreaterole" "nocreateuser" "noinherit"
  1688. "nologin" "none" "nosuperuser" "nothing" "notify" "nowait" "nullif"
  1689. "nulls" "object" "of" "oids" "operator" "option" "options" "out"
  1690. "overlay" "owned" "owner" "parser" "partial" "partition" "password"
  1691. "plans" "position" "preceding" "prepare" "prepared" "preserve" "prior"
  1692. "privileges" "procedural" "procedure" "quote" "range" "read"
  1693. "reassign" "recheck" "recursive" "reindex" "relative" "release"
  1694. "rename" "repeatable" "replace" "replica" "reset" "restart" "restrict"
  1695. "returns" "revoke" "role" "rollback" "row" "rows" "rule" "savepoint"
  1696. "schema" "scroll" "search" "second" "security" "sequence" "sequences"
  1697. "serializable" "server" "session" "set" "setof" "share" "show"
  1698. "simple" "stable" "standalone" "start" "statement" "statistics"
  1699. "stdin" "stdout" "storage" "strict" "strip" "substring" "superuser"
  1700. "sysid" "system" "tables" "tablespace" "temp" "template" "temporary"
  1701. "transaction" "treat" "trigger" "trim" "truncate" "trusted" "type"
  1702. "unbounded" "uncommitted" "unencrypted" "unknown" "unlisten" "until"
  1703. "update" "vacuum" "valid" "validator" "value" "values" "version"
  1704. "view" "volatile" "whitespace" "work" "wrapper" "write"
  1705. "xmlattributes" "xmlconcat" "xmlelement" "xmlforest" "xmlparse"
  1706. "xmlpi" "xmlroot" "xmlserialize" "year" "yes"
  1707. )
  1708. ;; Postgres Reserved
  1709. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1710. "all" "analyse" "analyze" "and" "any" "array" "asc" "as" "asymmetric"
  1711. "authorization" "binary" "both" "case" "cast" "check" "collate"
  1712. "column" "concurrently" "constraint" "create" "cross"
  1713. "current_catalog" "current_date" "current_role" "current_schema"
  1714. "current_time" "current_timestamp" "current_user" "default"
  1715. "deferrable" "desc" "distinct" "do" "else" "end" "except" "false"
  1716. "fetch" "foreign" "for" "freeze" "from" "full" "grant" "group"
  1717. "having" "ilike" "initially" "inner" "in" "intersect" "into" "isnull"
  1718. "is" "join" "leading" "left" "like" "limit" "localtime"
  1719. "localtimestamp" "natural" "notnull" "not" "null" "off" "offset"
  1720. "only" "on" "order" "or" "outer" "overlaps" "over" "placing" "primary"
  1721. "references" "returning" "right" "select" "session_user" "similar"
  1722. "some" "symmetric" "table" "then" "to" "trailing" "true" "union"
  1723. "unique" "user" "using" "variadic" "verbose" "when" "where" "window"
  1724. "with"
  1725. )
  1726. ;; Postgres Data Types
  1727. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1728. "bigint" "bigserial" "bit" "bool" "boolean" "box" "bytea" "char"
  1729. "character" "cidr" "circle" "date" "decimal" "double" "float4"
  1730. "float8" "inet" "int" "int2" "int4" "int8" "integer" "interval" "line"
  1731. "lseg" "macaddr" "money" "numeric" "path" "point" "polygon"
  1732. "precision" "real" "serial" "serial4" "serial8" "smallint" "text"
  1733. "time" "timestamp" "timestamptz" "timetz" "tsquery" "tsvector"
  1734. "txid_snapshot" "uuid" "varbit" "varchar" "varying" "without"
  1735. "xml" "zone"
  1736. )))
  1737. "Postgres SQL keywords used by font-lock.
  1738. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1739. regular expressions are created during compilation by calling the
  1740. function `regexp-opt'. Therefore, take a look at the source before
  1741. you define your own `sql-mode-postgres-font-lock-keywords'.")
  1742. (defvar sql-mode-linter-font-lock-keywords
  1743. (eval-when-compile
  1744. (list
  1745. ;; Linter Keywords
  1746. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1747. "autocommit" "autoinc" "autorowid" "cancel" "cascade" "channel"
  1748. "committed" "count" "countblob" "cross" "current" "data" "database"
  1749. "datafile" "datafiles" "datesplit" "dba" "dbname" "default" "deferred"
  1750. "denied" "description" "device" "difference" "directory" "error"
  1751. "escape" "euc" "exclusive" "external" "extfile" "false" "file"
  1752. "filename" "filesize" "filetime" "filter" "findblob" "first" "foreign"
  1753. "full" "fuzzy" "global" "granted" "ignore" "immediate" "increment"
  1754. "indexes" "indexfile" "indexfiles" "indextime" "initial" "integrity"
  1755. "internal" "key" "last_autoinc" "last_rowid" "limit" "linter"
  1756. "linter_file_device" "linter_file_size" "linter_name_length" "ln"
  1757. "local" "login" "maxisn" "maxrow" "maxrowid" "maxvalue" "message"
  1758. "minvalue" "module" "names" "national" "natural" "new" "new_table"
  1759. "no" "node" "noneuc" "nulliferror" "numbers" "off" "old" "old_table"
  1760. "only" "operation" "optimistic" "option" "page" "partially" "password"
  1761. "phrase" "plan" "precision" "primary" "priority" "privileges"
  1762. "proc_info_size" "proc_par_name_len" "protocol" "quant" "range" "raw"
  1763. "read" "record" "records" "references" "remote" "rename" "replication"
  1764. "restart" "rewrite" "root" "row" "rule" "savepoint" "security"
  1765. "sensitive" "sequence" "serializable" "server" "since" "size" "some"
  1766. "startup" "statement" "station" "success" "sys_guid" "tables" "test"
  1767. "timeout" "trace" "transaction" "translation" "trigger"
  1768. "trigger_info_size" "true" "trunc" "uncommitted" "unicode" "unknown"
  1769. "unlimited" "unlisted" "user" "utf8" "value" "varying" "volumes"
  1770. "wait" "windows_code" "workspace" "write" "xml"
  1771. )
  1772. ;; Linter Reserved
  1773. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1774. "access" "action" "add" "address" "after" "all" "alter" "always" "and"
  1775. "any" "append" "as" "asc" "ascic" "async" "at_begin" "at_end" "audit"
  1776. "aud_obj_name_len" "backup" "base" "before" "between" "blobfile"
  1777. "blobfiles" "blobpct" "brief" "browse" "by" "case" "cast" "check"
  1778. "clear" "close" "column" "comment" "commit" "connect" "contains"
  1779. "correct" "create" "delete" "desc" "disable" "disconnect" "distinct"
  1780. "drop" "each" "ef" "else" "enable" "end" "event" "except" "exclude"
  1781. "execute" "exists" "extract" "fetch" "finish" "for" "from" "get"
  1782. "grant" "group" "having" "identified" "in" "index" "inner" "insert"
  1783. "instead" "intersect" "into" "is" "isolation" "join" "left" "level"
  1784. "like" "lock" "mode" "modify" "not" "nowait" "null" "of" "on" "open"
  1785. "or" "order" "outer" "owner" "press" "prior" "procedure" "public"
  1786. "purge" "rebuild" "resource" "restrict" "revoke" "right" "role"
  1787. "rollback" "rownum" "select" "session" "set" "share" "shutdown"
  1788. "start" "stop" "sync" "synchronize" "synonym" "sysdate" "table" "then"
  1789. "to" "union" "unique" "unlock" "until" "update" "using" "values"
  1790. "view" "when" "where" "with" "without"
  1791. )
  1792. ;; Linter Functions
  1793. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1794. "abs" "acos" "asin" "atan" "atan2" "avg" "ceil" "cos" "cosh" "divtime"
  1795. "exp" "floor" "getbits" "getblob" "getbyte" "getlong" "getraw"
  1796. "getstr" "gettext" "getword" "hextoraw" "lenblob" "length" "log"
  1797. "lower" "lpad" "ltrim" "max" "min" "mod" "monthname" "nvl"
  1798. "octet_length" "power" "rand" "rawtohex" "repeat_string"
  1799. "right_substr" "round" "rpad" "rtrim" "sign" "sin" "sinh" "soundex"
  1800. "sqrt" "sum" "tan" "tanh" "timeint_to_days" "to_char" "to_date"
  1801. "to_gmtime" "to_localtime" "to_number" "trim" "upper" "decode"
  1802. "substr" "substring" "chr" "dayname" "days" "greatest" "hex" "initcap"
  1803. "instr" "least" "multime" "replace" "width"
  1804. )
  1805. ;; Linter Data Types
  1806. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1807. "bigint" "bitmap" "blob" "boolean" "char" "character" "date"
  1808. "datetime" "dec" "decimal" "double" "float" "int" "integer" "nchar"
  1809. "number" "numeric" "real" "smallint" "varbyte" "varchar" "byte"
  1810. "cursor" "long"
  1811. )))
  1812. "Linter SQL keywords used by font-lock.
  1813. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1814. regular expressions are created during compilation by calling the
  1815. function `regexp-opt'.")
  1816. (defvar sql-mode-ms-font-lock-keywords
  1817. (eval-when-compile
  1818. (list
  1819. ;; MS isql/osql Commands
  1820. (cons
  1821. (concat
  1822. "^\\(?:\\(?:set\\s-+\\(?:"
  1823. (regexp-opt '(
  1824. "datefirst" "dateformat" "deadlock_priority" "lock_timeout"
  1825. "concat_null_yields_null" "cursor_close_on_commit"
  1826. "disable_def_cnst_chk" "fips_flagger" "identity_insert" "language"
  1827. "offsets" "quoted_identifier" "arithabort" "arithignore" "fmtonly"
  1828. "nocount" "noexec" "numeric_roundabort" "parseonly"
  1829. "query_governor_cost_limit" "rowcount" "textsize" "ansi_defaults"
  1830. "ansi_null_dflt_off" "ansi_null_dflt_on" "ansi_nulls" "ansi_padding"
  1831. "ansi_warnings" "forceplan" "showplan_all" "showplan_text"
  1832. "statistics" "implicit_transactions" "remote_proc_transactions"
  1833. "transaction" "xact_abort"
  1834. ) t)
  1835. "\\)\\)\\|go\\s-*\\|use\\s-+\\|setuser\\s-+\\|dbcc\\s-+\\).*$")
  1836. 'font-lock-doc-face)
  1837. ;; MS Reserved
  1838. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1839. "absolute" "add" "all" "alter" "and" "any" "as" "asc" "authorization"
  1840. "avg" "backup" "begin" "between" "break" "browse" "bulk" "by"
  1841. "cascade" "case" "check" "checkpoint" "close" "clustered" "coalesce"
  1842. "column" "commit" "committed" "compute" "confirm" "constraint"
  1843. "contains" "containstable" "continue" "controlrow" "convert" "count"
  1844. "create" "cross" "current" "current_date" "current_time"
  1845. "current_timestamp" "current_user" "database" "deallocate" "declare"
  1846. "default" "delete" "deny" "desc" "disk" "distinct" "distributed"
  1847. "double" "drop" "dummy" "dump" "else" "end" "errlvl" "errorexit"
  1848. "escape" "except" "exec" "execute" "exists" "exit" "fetch" "file"
  1849. "fillfactor" "first" "floppy" "for" "foreign" "freetext"
  1850. "freetexttable" "from" "full" "goto" "grant" "group" "having"
  1851. "holdlock" "identity" "identity_insert" "identitycol" "if" "in"
  1852. "index" "inner" "insert" "intersect" "into" "is" "isolation" "join"
  1853. "key" "kill" "last" "left" "level" "like" "lineno" "load" "max" "min"
  1854. "mirrorexit" "national" "next" "nocheck" "nolock" "nonclustered" "not"
  1855. "null" "nullif" "of" "off" "offsets" "on" "once" "only" "open"
  1856. "opendatasource" "openquery" "openrowset" "option" "or" "order"
  1857. "outer" "output" "over" "paglock" "percent" "perm" "permanent" "pipe"
  1858. "plan" "precision" "prepare" "primary" "print" "prior" "privileges"
  1859. "proc" "procedure" "processexit" "public" "raiserror" "read"
  1860. "readcommitted" "readpast" "readtext" "readuncommitted" "reconfigure"
  1861. "references" "relative" "repeatable" "repeatableread" "replication"
  1862. "restore" "restrict" "return" "revoke" "right" "rollback" "rowcount"
  1863. "rowguidcol" "rowlock" "rule" "save" "schema" "select" "serializable"
  1864. "session_user" "set" "shutdown" "some" "statistics" "sum"
  1865. "system_user" "table" "tablock" "tablockx" "tape" "temp" "temporary"
  1866. "textsize" "then" "to" "top" "tran" "transaction" "trigger" "truncate"
  1867. "tsequal" "uncommitted" "union" "unique" "update" "updatetext"
  1868. "updlock" "use" "user" "values" "view" "waitfor" "when" "where"
  1869. "while" "with" "work" "writetext" "collate" "function" "openxml"
  1870. "returns"
  1871. )
  1872. ;; MS Functions
  1873. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1874. "@@connections" "@@cpu_busy" "@@cursor_rows" "@@datefirst" "@@dbts"
  1875. "@@error" "@@fetch_status" "@@identity" "@@idle" "@@io_busy"
  1876. "@@langid" "@@language" "@@lock_timeout" "@@max_connections"
  1877. "@@max_precision" "@@nestlevel" "@@options" "@@pack_received"
  1878. "@@pack_sent" "@@packet_errors" "@@procid" "@@remserver" "@@rowcount"
  1879. "@@servername" "@@servicename" "@@spid" "@@textsize" "@@timeticks"
  1880. "@@total_errors" "@@total_read" "@@total_write" "@@trancount"
  1881. "@@version" "abs" "acos" "and" "app_name" "ascii" "asin" "atan" "atn2"
  1882. "avg" "case" "cast" "ceiling" "char" "charindex" "coalesce"
  1883. "col_length" "col_name" "columnproperty" "containstable" "convert"
  1884. "cos" "cot" "count" "current_timestamp" "current_user" "cursor_status"
  1885. "databaseproperty" "datalength" "dateadd" "datediff" "datename"
  1886. "datepart" "day" "db_id" "db_name" "degrees" "difference" "exp"
  1887. "file_id" "file_name" "filegroup_id" "filegroup_name"
  1888. "filegroupproperty" "fileproperty" "floor" "formatmessage"
  1889. "freetexttable" "fulltextcatalogproperty" "fulltextserviceproperty"
  1890. "getansinull" "getdate" "grouping" "host_id" "host_name" "ident_incr"
  1891. "ident_seed" "identity" "index_col" "indexproperty" "is_member"
  1892. "is_srvrolemember" "isdate" "isnull" "isnumeric" "left" "len" "log"
  1893. "log10" "lower" "ltrim" "max" "min" "month" "nchar" "newid" "nullif"
  1894. "object_id" "object_name" "objectproperty" "openquery" "openrowset"
  1895. "parsename" "patindex" "patindex" "permissions" "pi" "power"
  1896. "quotename" "radians" "rand" "replace" "replicate" "reverse" "right"
  1897. "round" "rtrim" "session_user" "sign" "sin" "soundex" "space" "sqrt"
  1898. "square" "stats_date" "stdev" "stdevp" "str" "stuff" "substring" "sum"
  1899. "suser_id" "suser_name" "suser_sid" "suser_sname" "system_user" "tan"
  1900. "textptr" "textvalid" "typeproperty" "unicode" "upper" "user"
  1901. "user_id" "user_name" "var" "varp" "year"
  1902. )
  1903. ;; MS Variables
  1904. '("\\b@[a-zA-Z0-9_]*\\b" . font-lock-variable-name-face)
  1905. ;; MS Types
  1906. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  1907. "binary" "bit" "char" "character" "cursor" "datetime" "dec" "decimal"
  1908. "double" "float" "image" "int" "integer" "money" "national" "nchar"
  1909. "ntext" "numeric" "numeric" "nvarchar" "precision" "real"
  1910. "smalldatetime" "smallint" "smallmoney" "text" "timestamp" "tinyint"
  1911. "uniqueidentifier" "varbinary" "varchar" "varying"
  1912. )))
  1913. "Microsoft SQLServer SQL keywords used by font-lock.
  1914. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1915. regular expressions are created during compilation by calling the
  1916. function `regexp-opt'. Therefore, take a look at the source before
  1917. you define your own `sql-mode-ms-font-lock-keywords'.")
  1918. (defvar sql-mode-sybase-font-lock-keywords nil
  1919. "Sybase SQL keywords used by font-lock.
  1920. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1921. regular expressions are created during compilation by calling the
  1922. function `regexp-opt'. Therefore, take a look at the source before
  1923. you define your own `sql-mode-sybase-font-lock-keywords'.")
  1924. (defvar sql-mode-informix-font-lock-keywords nil
  1925. "Informix SQL keywords used by font-lock.
  1926. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1927. regular expressions are created during compilation by calling the
  1928. function `regexp-opt'. Therefore, take a look at the source before
  1929. you define your own `sql-mode-informix-font-lock-keywords'.")
  1930. (defvar sql-mode-interbase-font-lock-keywords nil
  1931. "Interbase SQL keywords used by font-lock.
  1932. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1933. regular expressions are created during compilation by calling the
  1934. function `regexp-opt'. Therefore, take a look at the source before
  1935. you define your own `sql-mode-interbase-font-lock-keywords'.")
  1936. (defvar sql-mode-ingres-font-lock-keywords nil
  1937. "Ingres SQL keywords used by font-lock.
  1938. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1939. regular expressions are created during compilation by calling the
  1940. function `regexp-opt'. Therefore, take a look at the source before
  1941. you define your own `sql-mode-interbase-font-lock-keywords'.")
  1942. (defvar sql-mode-solid-font-lock-keywords nil
  1943. "Solid SQL keywords used by font-lock.
  1944. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  1945. regular expressions are created during compilation by calling the
  1946. function `regexp-opt'. Therefore, take a look at the source before
  1947. you define your own `sql-mode-solid-font-lock-keywords'.")
  1948. (defvar sql-mode-mysql-font-lock-keywords
  1949. (eval-when-compile
  1950. (list
  1951. ;; MySQL Functions
  1952. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  1953. "ascii" "avg" "bdmpolyfromtext" "bdmpolyfromwkb" "bdpolyfromtext"
  1954. "bdpolyfromwkb" "benchmark" "bin" "bit_and" "bit_length" "bit_or"
  1955. "bit_xor" "both" "cast" "char_length" "character_length" "coalesce"
  1956. "concat" "concat_ws" "connection_id" "conv" "convert" "count"
  1957. "curdate" "current_date" "current_time" "current_timestamp" "curtime"
  1958. "elt" "encrypt" "export_set" "field" "find_in_set" "found_rows" "from"
  1959. "geomcollfromtext" "geomcollfromwkb" "geometrycollectionfromtext"
  1960. "geometrycollectionfromwkb" "geometryfromtext" "geometryfromwkb"
  1961. "geomfromtext" "geomfromwkb" "get_lock" "group_concat" "hex" "ifnull"
  1962. "instr" "interval" "isnull" "last_insert_id" "lcase" "leading"
  1963. "length" "linefromtext" "linefromwkb" "linestringfromtext"
  1964. "linestringfromwkb" "load_file" "locate" "lower" "lpad" "ltrim"
  1965. "make_set" "master_pos_wait" "max" "mid" "min" "mlinefromtext"
  1966. "mlinefromwkb" "mpointfromtext" "mpointfromwkb" "mpolyfromtext"
  1967. "mpolyfromwkb" "multilinestringfromtext" "multilinestringfromwkb"
  1968. "multipointfromtext" "multipointfromwkb" "multipolygonfromtext"
  1969. "multipolygonfromwkb" "now" "nullif" "oct" "octet_length" "ord"
  1970. "pointfromtext" "pointfromwkb" "polyfromtext" "polyfromwkb"
  1971. "polygonfromtext" "polygonfromwkb" "position" "quote" "rand"
  1972. "release_lock" "repeat" "replace" "reverse" "rpad" "rtrim" "soundex"
  1973. "space" "std" "stddev" "substring" "substring_index" "sum" "sysdate"
  1974. "trailing" "trim" "ucase" "unix_timestamp" "upper" "user" "variance"
  1975. )
  1976. ;; MySQL Keywords
  1977. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  1978. "action" "add" "after" "against" "all" "alter" "and" "as" "asc"
  1979. "auto_increment" "avg_row_length" "bdb" "between" "by" "cascade"
  1980. "case" "change" "character" "check" "checksum" "close" "collate"
  1981. "collation" "column" "columns" "comment" "committed" "concurrent"
  1982. "constraint" "create" "cross" "data" "database" "default"
  1983. "delay_key_write" "delayed" "delete" "desc" "directory" "disable"
  1984. "distinct" "distinctrow" "do" "drop" "dumpfile" "duplicate" "else" "elseif"
  1985. "enable" "enclosed" "end" "escaped" "exists" "fields" "first" "for"
  1986. "force" "foreign" "from" "full" "fulltext" "global" "group" "handler"
  1987. "having" "heap" "high_priority" "if" "ignore" "in" "index" "infile"
  1988. "inner" "insert" "insert_method" "into" "is" "isam" "isolation" "join"
  1989. "key" "keys" "last" "left" "level" "like" "limit" "lines" "load"
  1990. "local" "lock" "low_priority" "match" "max_rows" "merge" "min_rows"
  1991. "mode" "modify" "mrg_myisam" "myisam" "natural" "next" "no" "not"
  1992. "null" "offset" "oj" "on" "open" "optionally" "or" "order" "outer"
  1993. "outfile" "pack_keys" "partial" "password" "prev" "primary"
  1994. "procedure" "quick" "raid0" "raid_type" "read" "references" "rename"
  1995. "repeatable" "restrict" "right" "rollback" "rollup" "row_format"
  1996. "savepoint" "select" "separator" "serializable" "session" "set"
  1997. "share" "show" "sql_big_result" "sql_buffer_result" "sql_cache"
  1998. "sql_calc_found_rows" "sql_no_cache" "sql_small_result" "starting"
  1999. "straight_join" "striped" "table" "tables" "temporary" "terminated"
  2000. "then" "to" "transaction" "truncate" "type" "uncommitted" "union"
  2001. "unique" "unlock" "update" "use" "using" "values" "when" "where"
  2002. "with" "write" "xor"
  2003. )
  2004. ;; MySQL Data Types
  2005. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  2006. "bigint" "binary" "bit" "blob" "bool" "boolean" "char" "curve" "date"
  2007. "datetime" "dec" "decimal" "double" "enum" "fixed" "float" "geometry"
  2008. "geometrycollection" "int" "integer" "line" "linearring" "linestring"
  2009. "longblob" "longtext" "mediumblob" "mediumint" "mediumtext"
  2010. "multicurve" "multilinestring" "multipoint" "multipolygon"
  2011. "multisurface" "national" "numeric" "point" "polygon" "precision"
  2012. "real" "smallint" "surface" "text" "time" "timestamp" "tinyblob"
  2013. "tinyint" "tinytext" "unsigned" "varchar" "year" "year2" "year4"
  2014. "zerofill"
  2015. )))
  2016. "MySQL SQL keywords used by font-lock.
  2017. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  2018. regular expressions are created during compilation by calling the
  2019. function `regexp-opt'. Therefore, take a look at the source before
  2020. you define your own `sql-mode-mysql-font-lock-keywords'.")
  2021. (defvar sql-mode-sqlite-font-lock-keywords
  2022. (eval-when-compile
  2023. (list
  2024. ;; SQLite commands
  2025. '("^[.].*$" . font-lock-doc-face)
  2026. ;; SQLite Keyword
  2027. (sql-font-lock-keywords-builder 'font-lock-keyword-face nil
  2028. "abort" "action" "add" "after" "all" "alter" "analyze" "and" "as"
  2029. "asc" "attach" "autoincrement" "before" "begin" "between" "by"
  2030. "cascade" "case" "cast" "check" "collate" "column" "commit" "conflict"
  2031. "constraint" "create" "cross" "database" "default" "deferrable"
  2032. "deferred" "delete" "desc" "detach" "distinct" "drop" "each" "else"
  2033. "end" "escape" "except" "exclusive" "exists" "explain" "fail" "for"
  2034. "foreign" "from" "full" "glob" "group" "having" "if" "ignore"
  2035. "immediate" "in" "index" "indexed" "initially" "inner" "insert"
  2036. "instead" "intersect" "into" "is" "isnull" "join" "key" "left" "like"
  2037. "limit" "match" "natural" "no" "not" "notnull" "null" "of" "offset"
  2038. "on" "or" "order" "outer" "plan" "pragma" "primary" "query" "raise"
  2039. "references" "regexp" "reindex" "release" "rename" "replace"
  2040. "restrict" "right" "rollback" "row" "savepoint" "select" "set" "table"
  2041. "temp" "temporary" "then" "to" "transaction" "trigger" "union"
  2042. "unique" "update" "using" "vacuum" "values" "view" "virtual" "when"
  2043. "where"
  2044. )
  2045. ;; SQLite Data types
  2046. (sql-font-lock-keywords-builder 'font-lock-type-face nil
  2047. "int" "integer" "tinyint" "smallint" "mediumint" "bigint" "unsigned"
  2048. "big" "int2" "int8" "character" "varchar" "varying" "nchar" "native"
  2049. "nvarchar" "text" "clob" "blob" "real" "double" "precision" "float"
  2050. "numeric" "number" "decimal" "boolean" "date" "datetime"
  2051. )
  2052. ;; SQLite Functions
  2053. (sql-font-lock-keywords-builder 'font-lock-builtin-face nil
  2054. ;; Core functions
  2055. "abs" "changes" "coalesce" "glob" "ifnull" "hex" "last_insert_rowid"
  2056. "length" "like" "load_extension" "lower" "ltrim" "max" "min" "nullif"
  2057. "quote" "random" "randomblob" "replace" "round" "rtrim" "soundex"
  2058. "sqlite_compileoption_get" "sqlite_compileoption_used"
  2059. "sqlite_source_id" "sqlite_version" "substr" "total_changes" "trim"
  2060. "typeof" "upper" "zeroblob"
  2061. ;; Date/time functions
  2062. "time" "julianday" "strftime"
  2063. "current_date" "current_time" "current_timestamp"
  2064. ;; Aggregate functions
  2065. "avg" "count" "group_concat" "max" "min" "sum" "total"
  2066. )))
  2067. "SQLite SQL keywords used by font-lock.
  2068. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  2069. regular expressions are created during compilation by calling the
  2070. function `regexp-opt'. Therefore, take a look at the source before
  2071. you define your own `sql-mode-sqlite-font-lock-keywords'.")
  2072. (defvar sql-mode-db2-font-lock-keywords nil
  2073. "DB2 SQL keywords used by font-lock.
  2074. This variable is used by `sql-mode' and `sql-interactive-mode'. The
  2075. regular expressions are created during compilation by calling the
  2076. function `regexp-opt'. Therefore, take a look at the source before
  2077. you define your own `sql-mode-db2-font-lock-keywords'.")
  2078. (defvar sql-mode-font-lock-keywords nil
  2079. "SQL keywords used by font-lock.
  2080. Setting this variable directly no longer has any affect. Use
  2081. `sql-product' and `sql-add-product-keywords' to control the
  2082. highlighting rules in SQL mode.")
  2083. ;;; SQL Product support functions
  2084. (defun sql-read-product (prompt &optional initial)
  2085. "Read a valid SQL product."
  2086. (let ((init (or (and initial (symbol-name initial)) "ansi")))
  2087. (intern (completing-read
  2088. prompt
  2089. (mapcar (lambda (info) (symbol-name (car info)))
  2090. sql-product-alist)
  2091. nil 'require-match
  2092. init 'sql-product-history init))))
  2093. (defun sql-add-product (product display &rest plist)
  2094. "Add support for a database product in `sql-mode'.
  2095. Add PRODUCT to `sql-product-alist' which enables `sql-mode' to
  2096. properly support syntax highlighting and interactive interaction.
  2097. DISPLAY is the name of the SQL product that will appear in the
  2098. menu bar and in messages. PLIST initializes the product
  2099. configuration."
  2100. ;; Don't do anything if the product is already supported
  2101. (if (assoc product sql-product-alist)
  2102. (message "Product `%s' is already defined" product)
  2103. ;; Add product to the alist
  2104. (add-to-list 'sql-product-alist `((,product :name ,display . ,plist)))
  2105. ;; Add a menu item to the SQL->Product menu
  2106. (easy-menu-add-item sql-mode-menu '("Product")
  2107. ;; Each product is represented by a radio
  2108. ;; button with it's display name.
  2109. `[,display
  2110. (sql-set-product ',product)
  2111. :style radio
  2112. :selected (eq sql-product ',product)]
  2113. ;; Maintain the product list in
  2114. ;; (case-insensitive) alphabetic order of the
  2115. ;; display names. Loop thru each keymap item
  2116. ;; looking for an item whose display name is
  2117. ;; after this product's name.
  2118. (let ((next-item)
  2119. (down-display (downcase display)))
  2120. (map-keymap (lambda (k b)
  2121. (when (and (not next-item)
  2122. (string-lessp down-display
  2123. (downcase (cadr b))))
  2124. (setq next-item k)))
  2125. (easy-menu-get-map sql-mode-menu '("Product")))
  2126. next-item))
  2127. product))
  2128. (defun sql-del-product (product)
  2129. "Remove support for PRODUCT in `sql-mode'."
  2130. ;; Remove the menu item based on the display name
  2131. (easy-menu-remove-item sql-mode-menu '("Product") (sql-get-product-feature product :name))
  2132. ;; Remove the product alist item
  2133. (setq sql-product-alist (assq-delete-all product sql-product-alist))
  2134. nil)
  2135. (defun sql-set-product-feature (product feature newvalue)
  2136. "Set FEATURE of database PRODUCT to NEWVALUE.
  2137. The PRODUCT must be a symbol which identifies the database
  2138. product. The product must have already exist on the product
  2139. list. See `sql-add-product' to add new products. The FEATURE
  2140. argument must be a plist keyword accepted by
  2141. `sql-product-alist'."
  2142. (let* ((p (assoc product sql-product-alist))
  2143. (v (plist-get (cdr p) feature)))
  2144. (if p
  2145. (if (and
  2146. (member feature sql-indirect-features)
  2147. (symbolp v))
  2148. (set v newvalue)
  2149. (setcdr p (plist-put (cdr p) feature newvalue)))
  2150. (message "`%s' is not a known product; use `sql-add-product' to add it first." product))))
  2151. (defun sql-get-product-feature (product feature &optional fallback not-indirect)
  2152. "Lookup FEATURE associated with a SQL PRODUCT.
  2153. If the FEATURE is nil for PRODUCT, and FALLBACK is specified,
  2154. then the FEATURE associated with the FALLBACK product is
  2155. returned.
  2156. If the FEATURE is in the list `sql-indirect-features', and the
  2157. NOT-INDIRECT parameter is not set, then the value of the symbol
  2158. stored in the connect alist is returned.
  2159. See `sql-product-alist' for a list of products and supported features."
  2160. (let* ((p (assoc product sql-product-alist))
  2161. (v (plist-get (cdr p) feature)))
  2162. (if p
  2163. ;; If no value and fallback, lookup feature for fallback
  2164. (if (and (not v)
  2165. fallback
  2166. (not (eq product fallback)))
  2167. (sql-get-product-feature fallback feature)
  2168. (if (and
  2169. (member feature sql-indirect-features)
  2170. (not not-indirect)
  2171. (symbolp v))
  2172. (symbol-value v)
  2173. v))
  2174. (message "`%s' is not a known product; use `sql-add-product' to add it first." product)
  2175. nil)))
  2176. (defun sql-product-font-lock (keywords-only imenu)
  2177. "Configure font-lock and imenu with product-specific settings.
  2178. The KEYWORDS-ONLY flag is passed to font-lock to specify whether
  2179. only keywords should be highlighted and syntactic highlighting
  2180. skipped. The IMENU flag indicates whether `imenu-mode' should
  2181. also be configured."
  2182. (let
  2183. ;; Get the product-specific syntax-alist.
  2184. ((syntax-alist (sql-product-font-lock-syntax-alist)))
  2185. ;; Get the product-specific keywords.
  2186. (set (make-local-variable 'sql-mode-font-lock-keywords)
  2187. (append
  2188. (unless (eq sql-product 'ansi)
  2189. (sql-get-product-feature sql-product :font-lock))
  2190. ;; Always highlight ANSI keywords
  2191. (sql-get-product-feature 'ansi :font-lock)
  2192. ;; Fontify object names in CREATE, DROP and ALTER DDL
  2193. ;; statements
  2194. (list sql-mode-font-lock-object-name)))
  2195. ;; Setup font-lock. Force re-parsing of `font-lock-defaults'.
  2196. (kill-local-variable 'font-lock-set-defaults)
  2197. (set (make-local-variable 'font-lock-defaults)
  2198. (list 'sql-mode-font-lock-keywords
  2199. keywords-only t syntax-alist))
  2200. ;; Force font lock to reinitialize if it is already on
  2201. ;; Otherwise, we can wait until it can be started.
  2202. (when (and (fboundp 'font-lock-mode)
  2203. (boundp 'font-lock-mode)
  2204. font-lock-mode)
  2205. (font-lock-mode-internal nil)
  2206. (font-lock-mode-internal t))
  2207. (add-hook 'font-lock-mode-hook
  2208. (lambda ()
  2209. ;; Provide defaults for new font-lock faces.
  2210. (defvar font-lock-builtin-face
  2211. (if (boundp 'font-lock-preprocessor-face)
  2212. font-lock-preprocessor-face
  2213. font-lock-keyword-face))
  2214. (defvar font-lock-doc-face font-lock-string-face))
  2215. nil t)
  2216. ;; Setup imenu; it needs the same syntax-alist.
  2217. (when imenu
  2218. (setq imenu-syntax-alist syntax-alist))))
  2219. ;;;###autoload
  2220. (defun sql-add-product-keywords (product keywords &optional append)
  2221. "Add highlighting KEYWORDS for SQL PRODUCT.
  2222. PRODUCT should be a symbol, the name of a SQL product, such as
  2223. `oracle'. KEYWORDS should be a list; see the variable
  2224. `font-lock-keywords'. By default they are added at the beginning
  2225. of the current highlighting list. If optional argument APPEND is
  2226. `set', they are used to replace the current highlighting list.
  2227. If APPEND is any other non-nil value, they are added at the end
  2228. of the current highlighting list.
  2229. For example:
  2230. (sql-add-product-keywords 'ms
  2231. '((\"\\\\b\\\\w+_t\\\\b\" . font-lock-type-face)))
  2232. adds a fontification pattern to fontify identifiers ending in
  2233. `_t' as data types."
  2234. (let* ((sql-indirect-features nil)
  2235. (font-lock-var (sql-get-product-feature product :font-lock))
  2236. (old-val))
  2237. (setq old-val (symbol-value font-lock-var))
  2238. (set font-lock-var
  2239. (if (eq append 'set)
  2240. keywords
  2241. (if append
  2242. (append old-val keywords)
  2243. (append keywords old-val))))))
  2244. (defun sql-for-each-login (login-params body)
  2245. "Iterates through login parameters and returns a list of results."
  2246. (delq nil
  2247. (mapcar
  2248. (lambda (param)
  2249. (let ((token (or (and (listp param) (car param)) param))
  2250. (plist (or (and (listp param) (cdr param)) nil)))
  2251. (funcall body token plist)))
  2252. login-params)))
  2253. ;;; Functions to switch highlighting
  2254. (defun sql-product-syntax-table ()
  2255. (let ((table (copy-syntax-table sql-mode-syntax-table)))
  2256. (mapc (lambda (entry)
  2257. (modify-syntax-entry (car entry) (cdr entry) table))
  2258. (sql-get-product-feature sql-product :syntax-alist))
  2259. table))
  2260. (defun sql-product-font-lock-syntax-alist ()
  2261. (append
  2262. ;; Change all symbol character to word characters
  2263. (mapcar
  2264. (lambda (entry) (if (string= (substring (cdr entry) 0 1) "_")
  2265. (cons (car entry)
  2266. (concat "w" (substring (cdr entry) 1)))
  2267. entry))
  2268. (sql-get-product-feature sql-product :syntax-alist))
  2269. '((?_ . "w"))))
  2270. (defun sql-highlight-product ()
  2271. "Turn on the font highlighting for the SQL product selected."
  2272. (when (derived-mode-p 'sql-mode)
  2273. ;; Enhance the syntax table for the product
  2274. (set-syntax-table (sql-product-syntax-table))
  2275. ;; Setup font-lock
  2276. (sql-product-font-lock nil t)
  2277. ;; Set the mode name to include the product.
  2278. (setq mode-name (concat "SQL[" (or (sql-get-product-feature sql-product :name)
  2279. (symbol-name sql-product)) "]"))))
  2280. (defun sql-set-product (product)
  2281. "Set `sql-product' to PRODUCT and enable appropriate highlighting."
  2282. (interactive
  2283. (list (sql-read-product "SQL product: ")))
  2284. (if (stringp product) (setq product (intern product)))
  2285. (when (not (assoc product sql-product-alist))
  2286. (error "SQL product %s is not supported; treated as ANSI" product)
  2287. (setq product 'ansi))
  2288. ;; Save product setting and fontify.
  2289. (setq sql-product product)
  2290. (sql-highlight-product))
  2291. ;;; Compatibility functions
  2292. (if (not (fboundp 'comint-line-beginning-position))
  2293. ;; comint-line-beginning-position is defined in Emacs 21
  2294. (defun comint-line-beginning-position ()
  2295. "Return the buffer position of the beginning of the line, after any prompt.
  2296. The prompt is assumed to be any text at the beginning of the line
  2297. matching the regular expression `comint-prompt-regexp', a buffer
  2298. local variable."
  2299. (save-excursion (comint-bol nil) (point))))
  2300. ;;; Motion Functions
  2301. (defun sql-statement-regexp (prod)
  2302. (let* ((ansi-stmt (sql-get-product-feature 'ansi :statement))
  2303. (prod-stmt (sql-get-product-feature prod :statement)))
  2304. (concat "^\\<"
  2305. (if prod-stmt
  2306. ansi-stmt
  2307. (concat "\\(" ansi-stmt "\\|" prod-stmt "\\)"))
  2308. "\\>")))
  2309. (defun sql-beginning-of-statement (arg)
  2310. "Moves the cursor to the beginning of the current SQL statement."
  2311. (interactive "p")
  2312. (let ((here (point))
  2313. (regexp (sql-statement-regexp sql-product))
  2314. last next)
  2315. ;; Go to the end of the statement before the start we desire
  2316. (setq last (or (sql-end-of-statement (- arg))
  2317. (point-min)))
  2318. ;; And find the end after that
  2319. (setq next (or (sql-end-of-statement 1)
  2320. (point-max)))
  2321. ;; Our start must be between them
  2322. (goto-char last)
  2323. ;; Find an beginning-of-stmt that's not in a comment
  2324. (while (and (re-search-forward regexp next t 1)
  2325. (nth 7 (syntax-ppss)))
  2326. (goto-char (match-end 0)))
  2327. (goto-char
  2328. (if (match-data)
  2329. (match-beginning 0)
  2330. last))
  2331. (beginning-of-line)
  2332. ;; If we didn't move, try again
  2333. (when (= here (point))
  2334. (sql-beginning-of-statement (* 2 (sql-signum arg))))))
  2335. (defun sql-end-of-statement (arg)
  2336. "Moves the cursor to the end of the current SQL statement."
  2337. (interactive "p")
  2338. (let ((term (sql-get-product-feature sql-product :terminator))
  2339. (re-search (if (> 0 arg) 're-search-backward 're-search-forward))
  2340. (here (point))
  2341. (n 0))
  2342. (when (consp term)
  2343. (setq term (car term)))
  2344. ;; Iterate until we've moved the desired number of stmt ends
  2345. (while (not (= (sql-signum arg) 0))
  2346. ;; if we're looking at the terminator, jump by 2
  2347. (if (or (and (> 0 arg) (looking-back term))
  2348. (and (< 0 arg) (looking-at term)))
  2349. (setq n 2)
  2350. (setq n 1))
  2351. ;; If we found another end-of-stmt
  2352. (if (not (apply re-search term nil t n nil))
  2353. (setq arg 0)
  2354. ;; count it if we're not in a comment
  2355. (unless (nth 7 (syntax-ppss))
  2356. (setq arg (- arg (sql-signum arg))))))
  2357. (goto-char (if (match-data)
  2358. (match-end 0)
  2359. here))))
  2360. ;;; Small functions
  2361. (defun sql-magic-go (arg)
  2362. "Insert \"o\" and call `comint-send-input'.
  2363. `sql-electric-stuff' must be the symbol `go'."
  2364. (interactive "P")
  2365. (self-insert-command (prefix-numeric-value arg))
  2366. (if (and (equal sql-electric-stuff 'go)
  2367. (save-excursion
  2368. (comint-bol nil)
  2369. (looking-at "go\\b")))
  2370. (comint-send-input)))
  2371. (defun sql-magic-semicolon (arg)
  2372. "Insert semicolon and call `comint-send-input'.
  2373. `sql-electric-stuff' must be the symbol `semicolon'."
  2374. (interactive "P")
  2375. (self-insert-command (prefix-numeric-value arg))
  2376. (if (equal sql-electric-stuff 'semicolon)
  2377. (comint-send-input)))
  2378. (defun sql-accumulate-and-indent ()
  2379. "Continue SQL statement on the next line."
  2380. (interactive)
  2381. (if (fboundp 'comint-accumulate)
  2382. (comint-accumulate)
  2383. (newline))
  2384. (indent-according-to-mode))
  2385. (defun sql-help-list-products (indent freep)
  2386. "Generate listing of products available for use under SQLi.
  2387. List products with :free-software attribute set to FREEP. Indent
  2388. each line with INDENT."
  2389. (let (sqli-func doc)
  2390. (setq doc "")
  2391. (dolist (p sql-product-alist)
  2392. (setq sqli-func (intern (concat "sql-" (symbol-name (car p)))))
  2393. (if (and (fboundp sqli-func)
  2394. (eq (sql-get-product-feature (car p) :free-software) freep))
  2395. (setq doc
  2396. (concat doc
  2397. indent
  2398. (or (sql-get-product-feature (car p) :name)
  2399. (symbol-name (car p)))
  2400. ":\t"
  2401. "\\["
  2402. (symbol-name sqli-func)
  2403. "]\n"))))
  2404. doc))
  2405. ;;;###autoload
  2406. (defun sql-help ()
  2407. "Show short help for the SQL modes.
  2408. Use an entry function to open an interactive SQL buffer. This buffer is
  2409. usually named `*SQL*'. The name of the major mode is SQLi.
  2410. Use the following commands to start a specific SQL interpreter:
  2411. \\\\FREE
  2412. Other non-free SQL implementations are also supported:
  2413. \\\\NONFREE
  2414. But we urge you to choose a free implementation instead of these.
  2415. You can also use \\[sql-product-interactive] to invoke the
  2416. interpreter for the current `sql-product'.
  2417. Once you have the SQLi buffer, you can enter SQL statements in the
  2418. buffer. The output generated is appended to the buffer and a new prompt
  2419. is generated. See the In/Out menu in the SQLi buffer for some functions
  2420. that help you navigate through the buffer, the input history, etc.
  2421. If you have a really complex SQL statement or if you are writing a
  2422. procedure, you can do this in a separate buffer. Put the new buffer in
  2423. `sql-mode' by calling \\[sql-mode]. The name of this buffer can be
  2424. anything. The name of the major mode is SQL.
  2425. In this SQL buffer (SQL mode), you can send the region or the entire
  2426. buffer to the interactive SQL buffer (SQLi mode). The results are
  2427. appended to the SQLi buffer without disturbing your SQL buffer."
  2428. (interactive)
  2429. ;; Insert references to loaded products into the help buffer string
  2430. (let ((doc (documentation 'sql-help t))
  2431. changedp)
  2432. (setq changedp nil)
  2433. ;; Insert FREE software list
  2434. (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]FREE\\s-*\n" doc 0)
  2435. (setq doc (replace-match (sql-help-list-products (match-string 1 doc) t)
  2436. t t doc 0)
  2437. changedp t))
  2438. ;; Insert non-FREE software list
  2439. (when (string-match "^\\(\\s-*\\)[\\\\][\\\\]NONFREE\\s-*\n" doc 0)
  2440. (setq doc (replace-match (sql-help-list-products (match-string 1 doc) nil)
  2441. t t doc 0)
  2442. changedp t))
  2443. ;; If we changed the help text, save the change so that the help
  2444. ;; sub-system will see it
  2445. (when changedp
  2446. (put 'sql-help 'function-documentation doc)))
  2447. ;; Call help on this function
  2448. (describe-function 'sql-help))
  2449. (defun sql-read-passwd (prompt &optional default)
  2450. "Read a password using PROMPT. Optional DEFAULT is password to start with."
  2451. (read-passwd prompt nil default))
  2452. (defun sql-get-login-ext (symbol prompt history-var plist)
  2453. "Prompt user with extended login parameters.
  2454. The global value of SYMBOL is the last value and the global value
  2455. of the SYMBOL is set based on the user's input.
  2456. If PLIST is nil, then the user is simply prompted for a string
  2457. value.
  2458. The property `:default' specifies the default value. If the
  2459. `:number' property is non-nil then ask for a number.
  2460. The `:file' property prompts for a file name that must match the
  2461. regexp pattern specified in its value.
  2462. The `:completion' property prompts for a string specified by its
  2463. value. (The property value is used as the PREDICATE argument to
  2464. `completing-read'.)"
  2465. (set-default
  2466. symbol
  2467. (let* ((default (plist-get plist :default))
  2468. (last-value (default-value symbol))
  2469. (prompt-def
  2470. (if default
  2471. (if (string-match "\\(\\):[ \t]*\\'" prompt)
  2472. (replace-match (format " (default \"%s\")" default) t t prompt 1)
  2473. (replace-regexp-in-string "[ \t]*\\'"
  2474. (format " (default \"%s\") " default)
  2475. prompt t t))
  2476. prompt))
  2477. (use-dialog-box nil))
  2478. (cond
  2479. ((plist-member plist :file)
  2480. (expand-file-name
  2481. (read-file-name prompt
  2482. (file-name-directory last-value) default t
  2483. (file-name-nondirectory last-value)
  2484. (when (plist-get plist :file)
  2485. `(lambda (f)
  2486. (string-match
  2487. (concat "\\<" ,(plist-get plist :file) "\\>")
  2488. (file-name-nondirectory f)))))))
  2489. ((plist-member plist :completion)
  2490. (completing-read prompt-def (plist-get plist :completion) nil t
  2491. last-value history-var default))
  2492. ((plist-get plist :number)
  2493. (read-number prompt (or default last-value 0)))
  2494. (t
  2495. (let ((r (read-from-minibuffer prompt-def last-value nil nil history-var nil)))
  2496. (if (string= "" r) (or default "") r)))))))
  2497. (defun sql-get-login (&rest what)
  2498. "Get username, password and database from the user.
  2499. The variables `sql-user', `sql-password', `sql-server', and
  2500. `sql-database' can be customized. They are used as the default values.
  2501. Usernames, servers and databases are stored in `sql-user-history',
  2502. `sql-server-history' and `database-history'. Passwords are not stored
  2503. in a history.
  2504. Parameter WHAT is a list of tokens passed as arguments in the
  2505. function call. The function asks for the username if WHAT
  2506. contains the symbol `user', for the password if it contains the
  2507. symbol `password', for the server if it contains the symbol
  2508. `server', and for the database if it contains the symbol
  2509. `database'. The members of WHAT are processed in the order in
  2510. which they are provided.
  2511. Each token may also be a list with the token in the car and a
  2512. plist of options as the cdr. The following properties are
  2513. supported:
  2514. :file <filename-regexp>
  2515. :completion <list-of-strings-or-function>
  2516. :default <default-value>
  2517. :number t
  2518. In order to ask the user for username, password and database, call the
  2519. function like this: (sql-get-login 'user 'password 'database)."
  2520. (interactive)
  2521. (mapcar
  2522. (lambda (w)
  2523. (let ((token (or (and (consp w) (car w)) w))
  2524. (plist (or (and (consp w) (cdr w)) nil)))
  2525. (cond
  2526. ((eq token 'user) ; user
  2527. (sql-get-login-ext 'sql-user "User: " 'sql-user-history plist))
  2528. ((eq token 'password) ; password
  2529. (setq-default sql-password
  2530. (sql-read-passwd "Password: " sql-password)))
  2531. ((eq token 'server) ; server
  2532. (sql-get-login-ext 'sql-server "Server: " 'sql-server-history plist))
  2533. ((eq token 'database) ; database
  2534. (sql-get-login-ext 'sql-database "Database: " 'sql-database-history plist))
  2535. ((eq token 'port) ; port
  2536. (sql-get-login-ext 'sql-port "Port: " nil (append '(:number t) plist))))))
  2537. what))
  2538. (defun sql-find-sqli-buffer (&optional product connection)
  2539. "Returns the name of the current default SQLi buffer or nil.
  2540. In order to qualify, the SQLi buffer must be alive, be in
  2541. `sql-interactive-mode' and have a process."
  2542. (let ((buf sql-buffer)
  2543. (prod (or product sql-product)))
  2544. (or
  2545. ;; Current sql-buffer, if there is one.
  2546. (and (sql-buffer-live-p buf prod connection)
  2547. buf)
  2548. ;; Global sql-buffer
  2549. (and (setq buf (default-value 'sql-buffer))
  2550. (sql-buffer-live-p buf prod connection)
  2551. buf)
  2552. ;; Look thru each buffer
  2553. (car (apply 'append
  2554. (mapcar (lambda (b)
  2555. (and (sql-buffer-live-p b prod connection)
  2556. (list (buffer-name b))))
  2557. (buffer-list)))))))
  2558. (defun sql-set-sqli-buffer-generally ()
  2559. "Set SQLi buffer for all SQL buffers that have none.
  2560. This function checks all SQL buffers for their SQLi buffer. If their
  2561. SQLi buffer is nonexistent or has no process, it is set to the current
  2562. default SQLi buffer. The current default SQLi buffer is determined
  2563. using `sql-find-sqli-buffer'. If `sql-buffer' is set,
  2564. `sql-set-sqli-hook' is run."
  2565. (interactive)
  2566. (save-excursion
  2567. (let ((buflist (buffer-list))
  2568. (default-buffer (sql-find-sqli-buffer)))
  2569. (setq-default sql-buffer default-buffer)
  2570. (while (not (null buflist))
  2571. (let ((candidate (car buflist)))
  2572. (set-buffer candidate)
  2573. (if (and (derived-mode-p 'sql-mode)
  2574. (not (sql-buffer-live-p sql-buffer)))
  2575. (progn
  2576. (setq sql-buffer default-buffer)
  2577. (when default-buffer
  2578. (run-hooks 'sql-set-sqli-hook)))))
  2579. (setq buflist (cdr buflist))))))
  2580. (defun sql-set-sqli-buffer ()
  2581. "Set the SQLi buffer SQL strings are sent to.
  2582. Call this function in a SQL buffer in order to set the SQLi buffer SQL
  2583. strings are sent to. Calling this function sets `sql-buffer' and runs
  2584. `sql-set-sqli-hook'.
  2585. If you call it from a SQL buffer, this sets the local copy of
  2586. `sql-buffer'.
  2587. If you call it from anywhere else, it sets the global copy of
  2588. `sql-buffer'."
  2589. (interactive)
  2590. (let ((default-buffer (sql-find-sqli-buffer)))
  2591. (if (null default-buffer)
  2592. (error "There is no suitable SQLi buffer")
  2593. (let ((new-buffer (read-buffer "New SQLi buffer: " default-buffer t)))
  2594. (if (null (sql-buffer-live-p new-buffer))
  2595. (error "Buffer %s is not a working SQLi buffer" new-buffer)
  2596. (when new-buffer
  2597. (setq sql-buffer new-buffer)
  2598. (run-hooks 'sql-set-sqli-hook)))))))
  2599. (defun sql-show-sqli-buffer ()
  2600. "Show the name of current SQLi buffer.
  2601. This is the buffer SQL strings are sent to. It is stored in the
  2602. variable `sql-buffer'. See `sql-help' on how to create such a buffer."
  2603. (interactive)
  2604. (if (or (null sql-buffer)
  2605. (null (buffer-live-p (get-buffer sql-buffer))))
  2606. (message "%s has no SQLi buffer set." (buffer-name (current-buffer)))
  2607. (if (null (get-buffer-process sql-buffer))
  2608. (message "Buffer %s has no process." sql-buffer)
  2609. (message "Current SQLi buffer is %s." sql-buffer))))
  2610. (defun sql-make-alternate-buffer-name ()
  2611. "Return a string that can be used to rename a SQLi buffer.
  2612. This is used to set `sql-alternate-buffer-name' within
  2613. `sql-interactive-mode'.
  2614. If the session was started with `sql-connect' then the alternate
  2615. name would be the name of the connection.
  2616. Otherwise, it uses the parameters identified by the :sqlilogin
  2617. parameter.
  2618. If all else fails, the alternate name would be the user and
  2619. server/database name."
  2620. (let ((name ""))
  2621. ;; Build a name using the :sqli-login setting
  2622. (setq name
  2623. (apply 'concat
  2624. (cdr
  2625. (apply 'append nil
  2626. (sql-for-each-login
  2627. (sql-get-product-feature sql-product :sqli-login)
  2628. (lambda (token plist)
  2629. (cond
  2630. ((eq token 'user)
  2631. (unless (string= "" sql-user)
  2632. (list "/" sql-user)))
  2633. ((eq token 'port)
  2634. (unless (or (not (numberp sql-port))
  2635. (= 0 sql-port))
  2636. (list ":" (number-to-string sql-port))))
  2637. ((eq token 'server)
  2638. (unless (string= "" sql-server)
  2639. (list "."
  2640. (if (plist-member plist :file)
  2641. (file-name-nondirectory sql-server)
  2642. sql-server))))
  2643. ((eq token 'database)
  2644. (unless (string= "" sql-database)
  2645. (list "@"
  2646. (if (plist-member plist :file)
  2647. (file-name-nondirectory sql-database)
  2648. sql-database))))
  2649. ((eq token 'password) nil)
  2650. (t nil))))))))
  2651. ;; If there's a connection, use it and the name thus far
  2652. (if sql-connection
  2653. (format "<%s>%s" sql-connection (or name ""))
  2654. ;; If there is no name, try to create something meaningful
  2655. (if (string= "" (or name ""))
  2656. (concat
  2657. (if (string= "" sql-user)
  2658. (if (string= "" (user-login-name))
  2659. ()
  2660. (concat (user-login-name) "/"))
  2661. (concat sql-user "/"))
  2662. (if (string= "" sql-database)
  2663. (if (string= "" sql-server)
  2664. (system-name)
  2665. sql-server)
  2666. sql-database))
  2667. ;; Use the name we've got
  2668. name))))
  2669. (defun sql-rename-buffer (&optional new-name)
  2670. "Rename a SQL interactive buffer.
  2671. Prompts for the new name if command is preceded by
  2672. \\[universal-argument]. If no buffer name is provided, then the
  2673. `sql-alternate-buffer-name' is used.
  2674. The actual buffer name set will be \"*SQL: NEW-NAME*\". If
  2675. NEW-NAME is empty, then the buffer name will be \"*SQL*\"."
  2676. (interactive "P")
  2677. (if (not (derived-mode-p 'sql-interactive-mode))
  2678. (message "Current buffer is not a SQL interactive buffer")
  2679. (setq sql-alternate-buffer-name
  2680. (cond
  2681. ((stringp new-name) new-name)
  2682. ((consp new-name)
  2683. (read-string "Buffer name (\"*SQL: XXX*\"; enter `XXX'): "
  2684. sql-alternate-buffer-name))
  2685. (t sql-alternate-buffer-name)))
  2686. (rename-buffer (if (string= "" sql-alternate-buffer-name)
  2687. "*SQL*"
  2688. (format "*SQL: %s*" sql-alternate-buffer-name))
  2689. t)))
  2690. (defun sql-copy-column ()
  2691. "Copy current column to the end of buffer.
  2692. Inserts SELECT or commas if appropriate."
  2693. (interactive)
  2694. (let ((column))
  2695. (save-excursion
  2696. (setq column (buffer-substring-no-properties
  2697. (progn (forward-char 1) (backward-sexp 1) (point))
  2698. (progn (forward-sexp 1) (point))))
  2699. (goto-char (point-max))
  2700. (let ((bol (comint-line-beginning-position)))
  2701. (cond
  2702. ;; if empty command line, insert SELECT
  2703. ((= bol (point))
  2704. (insert "SELECT "))
  2705. ;; else if appending to INTO .* (, SELECT or ORDER BY, insert a comma
  2706. ((save-excursion
  2707. (re-search-backward "\\b\\(\\(into\\s-+\\S-+\\s-+(\\)\\|select\\|order by\\) .+"
  2708. bol t))
  2709. (insert ", "))
  2710. ;; else insert a space
  2711. (t
  2712. (if (eq (preceding-char) ?\s)
  2713. nil
  2714. (insert " ")))))
  2715. ;; in any case, insert the column
  2716. (insert column)
  2717. (message "%s" column))))
  2718. ;; On Windows, SQL*Plus for Oracle turns on full buffering for stdout
  2719. ;; if it is not attached to a character device; therefore placeholder
  2720. ;; replacement by SQL*Plus is fully buffered. The workaround lets
  2721. ;; Emacs query for the placeholders.
  2722. (defvar sql-placeholder-history nil
  2723. "History of placeholder values used.")
  2724. (defun sql-placeholders-filter (string)
  2725. "Replace placeholders in STRING.
  2726. Placeholders are words starting with an ampersand like &this."
  2727. (when sql-oracle-scan-on
  2728. (while (string-match "&\\(\\sw+\\)" string)
  2729. (setq string (replace-match
  2730. (read-from-minibuffer
  2731. (format "Enter value for %s: " (match-string 1 string))
  2732. nil nil nil 'sql-placeholder-history)
  2733. t t string))))
  2734. string)
  2735. ;; Using DB2 interactively, newlines must be escaped with " \".
  2736. ;; The space before the backslash is relevant.
  2737. (defun sql-escape-newlines-filter (string)
  2738. "Escape newlines in STRING.
  2739. Every newline in STRING will be preceded with a space and a backslash."
  2740. (let ((result "") (start 0) mb me)
  2741. (while (string-match "\n" string start)
  2742. (setq mb (match-beginning 0)
  2743. me (match-end 0)
  2744. result (concat result
  2745. (substring string start mb)
  2746. (if (and (> mb 1)
  2747. (string-equal " \\" (substring string (- mb 2) mb)))
  2748. "" " \\\n"))
  2749. start me))
  2750. (concat result (substring string start))))
  2751. ;;; Input sender for SQLi buffers
  2752. (defvar sql-output-newline-count 0
  2753. "Number of newlines in the input string.
  2754. Allows the suppression of continuation prompts.")
  2755. (defvar sql-output-by-send nil
  2756. "Non-nil if the command in the input was generated by `sql-send-string'.")
  2757. (defun sql-input-sender (proc string)
  2758. "Send STRING to PROC after applying filters."
  2759. (let* ((product (with-current-buffer (process-buffer proc) sql-product))
  2760. (filter (sql-get-product-feature product :input-filter)))
  2761. ;; Apply filter(s)
  2762. (cond
  2763. ((not filter)
  2764. nil)
  2765. ((functionp filter)
  2766. (setq string (funcall filter string)))
  2767. ((listp filter)
  2768. (mapc (lambda (f) (setq string (funcall f string))) filter))
  2769. (t nil))
  2770. ;; Count how many newlines in the string
  2771. (setq sql-output-newline-count 0)
  2772. (mapc (lambda (ch)
  2773. (when (eq ch ?\n)
  2774. (setq sql-output-newline-count (1+ sql-output-newline-count))))
  2775. string)
  2776. ;; Send the string
  2777. (comint-simple-send proc string)))
  2778. ;;; Strip out continuation prompts
  2779. (defvar sql-preoutput-hold nil)
  2780. (defun sql-interactive-remove-continuation-prompt (oline)
  2781. "Strip out continuation prompts out of the OLINE.
  2782. Added to the `comint-preoutput-filter-functions' hook in a SQL
  2783. interactive buffer. If `sql-output-newline-count' is greater than
  2784. zero, then an output line matching the continuation prompt is filtered
  2785. out. If the count is zero, then a newline is inserted into the output
  2786. to force the output from the query to appear on a new line.
  2787. The complication to this filter is that the continuation prompts
  2788. may arrive in multiple chunks. If they do, then the function
  2789. saves any unfiltered output in a buffer and prepends that buffer
  2790. to the next chunk to properly match the broken-up prompt.
  2791. If the filter gets confused, it should reset and stop filtering
  2792. to avoid deleting non-prompt output."
  2793. (let (did-filter)
  2794. (setq oline (concat (or sql-preoutput-hold "") oline)
  2795. sql-preoutput-hold nil)
  2796. (if (and comint-prompt-regexp
  2797. (integerp sql-output-newline-count)
  2798. (>= sql-output-newline-count 1))
  2799. (progn
  2800. (while (and (not (string= oline ""))
  2801. (> sql-output-newline-count 0)
  2802. (string-match comint-prompt-regexp oline)
  2803. (= (match-beginning 0) 0))
  2804. (setq oline (replace-match "" nil nil oline)
  2805. sql-output-newline-count (1- sql-output-newline-count)
  2806. did-filter t))
  2807. (if (= sql-output-newline-count 0)
  2808. (setq sql-output-newline-count nil
  2809. oline (concat "\n" oline)
  2810. sql-output-by-send nil)
  2811. (setq sql-preoutput-hold oline
  2812. oline ""))
  2813. (unless did-filter
  2814. (setq oline (or sql-preoutput-hold "")
  2815. sql-preoutput-hold nil
  2816. sql-output-newline-count nil)))
  2817. (setq sql-output-newline-count nil))
  2818. oline))
  2819. ;;; Sending the region to the SQLi buffer.
  2820. (defun sql-send-string (str)
  2821. "Send the string STR to the SQL process."
  2822. (interactive "sSQL Text: ")
  2823. (let ((comint-input-sender-no-newline nil)
  2824. (s (replace-regexp-in-string "[[:space:]\n\r]+\\'" "" str)))
  2825. (if (sql-buffer-live-p sql-buffer)
  2826. (progn
  2827. ;; Ignore the hoping around...
  2828. (save-excursion
  2829. ;; Set product context
  2830. (with-current-buffer sql-buffer
  2831. ;; Send the string (trim the trailing whitespace)
  2832. (sql-input-sender (get-buffer-process sql-buffer) s)
  2833. ;; Send a command terminator if we must
  2834. (if sql-send-terminator
  2835. (sql-send-magic-terminator sql-buffer s sql-send-terminator))
  2836. (message "Sent string to buffer %s." sql-buffer)))
  2837. ;; Display the sql buffer
  2838. (if sql-pop-to-buffer-after-send-region
  2839. (pop-to-buffer sql-buffer)
  2840. (display-buffer sql-buffer)))
  2841. ;; We don't have no stinkin' sql
  2842. (message "No SQL process started."))))
  2843. (defun sql-send-region (start end)
  2844. "Send a region to the SQL process."
  2845. (interactive "r")
  2846. (sql-send-string (buffer-substring-no-properties start end)))
  2847. (defun sql-send-paragraph ()
  2848. "Send the current paragraph to the SQL process."
  2849. (interactive)
  2850. (let ((start (save-excursion
  2851. (backward-paragraph)
  2852. (point)))
  2853. (end (save-excursion
  2854. (forward-paragraph)
  2855. (point))))
  2856. (sql-send-region start end)))
  2857. (defun sql-send-buffer ()
  2858. "Send the buffer contents to the SQL process."
  2859. (interactive)
  2860. (sql-send-region (point-min) (point-max)))
  2861. (defun sql-send-magic-terminator (buf str terminator)
  2862. "Send TERMINATOR to buffer BUF if its not present in STR."
  2863. (let (comint-input-sender-no-newline pat term)
  2864. ;; If flag is merely on(t), get product-specific terminator
  2865. (if (eq terminator t)
  2866. (setq terminator (sql-get-product-feature sql-product :terminator)))
  2867. ;; If there is no terminator specified, use default ";"
  2868. (unless terminator
  2869. (setq terminator ";"))
  2870. ;; Parse the setting into the pattern and the terminator string
  2871. (cond ((stringp terminator)
  2872. (setq pat (regexp-quote terminator)
  2873. term terminator))
  2874. ((consp terminator)
  2875. (setq pat (car terminator)
  2876. term (cdr terminator)))
  2877. (t
  2878. nil))
  2879. ;; Check to see if the pattern is present in the str already sent
  2880. (unless (and pat term
  2881. (string-match (concat pat "\\'") str))
  2882. (comint-simple-send (get-buffer-process buf) term)
  2883. (setq sql-output-newline-count
  2884. (if sql-output-newline-count
  2885. (1+ sql-output-newline-count)
  2886. 1)))
  2887. (setq sql-output-by-send t)))
  2888. (defun sql-remove-tabs-filter (str)
  2889. "Replace tab characters with spaces."
  2890. (replace-regexp-in-string "\t" " " str nil t))
  2891. (defun sql-toggle-pop-to-buffer-after-send-region (&optional value)
  2892. "Toggle `sql-pop-to-buffer-after-send-region'.
  2893. If given the optional parameter VALUE, sets
  2894. `sql-toggle-pop-to-buffer-after-send-region' to VALUE."
  2895. (interactive "P")
  2896. (if value
  2897. (setq sql-pop-to-buffer-after-send-region value)
  2898. (setq sql-pop-to-buffer-after-send-region
  2899. (null sql-pop-to-buffer-after-send-region))))
  2900. ;;; Redirect output functions
  2901. (defvar sql-debug-redirect nil
  2902. "If non-nil, display messages related to the use of redirection.")
  2903. (defun sql-str-literal (s)
  2904. (concat "'" (replace-regexp-in-string "[']" "''" s) "'"))
  2905. (defun sql-redirect (sqlbuf command &optional outbuf save-prior)
  2906. "Execute the SQL command and send output to OUTBUF.
  2907. SQLBUF must be an active SQL interactive buffer. OUTBUF may be
  2908. an existing buffer, or the name of a non-existing buffer. If
  2909. omitted the output is sent to a temporary buffer which will be
  2910. killed after the command completes. COMMAND should be a string
  2911. of commands accepted by the SQLi program. COMMAND may also be a
  2912. list of SQLi command strings."
  2913. (let* ((visible (and outbuf
  2914. (not (string= " " (substring outbuf 0 1))))))
  2915. (when visible
  2916. (message "Executing SQL command..."))
  2917. (if (consp command)
  2918. (mapc (lambda (c) (sql-redirect-one sqlbuf c outbuf save-prior))
  2919. command)
  2920. (sql-redirect-one sqlbuf command outbuf save-prior))
  2921. (when visible
  2922. (message "Executing SQL command...done"))))
  2923. (defun sql-redirect-one (sqlbuf command outbuf save-prior)
  2924. (with-current-buffer sqlbuf
  2925. (let ((buf (get-buffer-create (or outbuf " *SQL-Redirect*")))
  2926. (proc (get-buffer-process (current-buffer)))
  2927. (comint-prompt-regexp (sql-get-product-feature sql-product
  2928. :prompt-regexp))
  2929. (start nil))
  2930. (with-current-buffer buf
  2931. (setq view-read-only nil)
  2932. (unless save-prior
  2933. (erase-buffer))
  2934. (goto-char (point-max))
  2935. (unless (zerop (buffer-size))
  2936. (insert "\n"))
  2937. (setq start (point)))
  2938. (when sql-debug-redirect
  2939. (message ">>SQL> %S" command))
  2940. ;; Run the command
  2941. (comint-redirect-send-command-to-process command buf proc nil t)
  2942. (while (null comint-redirect-completed)
  2943. (accept-process-output nil 1))
  2944. ;; Clean up the output results
  2945. (with-current-buffer buf
  2946. ;; Remove trailing whitespace
  2947. (goto-char (point-max))
  2948. (when (looking-back "[ \t\f\n\r]*" start)
  2949. (delete-region (match-beginning 0) (match-end 0)))
  2950. ;; Remove echo if there was one
  2951. (goto-char start)
  2952. (when (looking-at (concat "^" (regexp-quote command) "[\\n]"))
  2953. (delete-region (match-beginning 0) (match-end 0)))
  2954. ;; Remove Ctrl-Ms
  2955. (goto-char start)
  2956. (while (re-search-forward "\r+$" nil t)
  2957. (replace-match "" t t))
  2958. (goto-char start)))))
  2959. (defun sql-redirect-value (sqlbuf command regexp &optional regexp-groups)
  2960. "Execute the SQL command and return part of result.
  2961. SQLBUF must be an active SQL interactive buffer. COMMAND should
  2962. be a string of commands accepted by the SQLi program. From the
  2963. output, the REGEXP is repeatedly matched and the list of
  2964. REGEXP-GROUPS submatches is returned. This behaves much like
  2965. \\[comint-redirect-results-list-from-process] but instead of
  2966. returning a single submatch it returns a list of each submatch
  2967. for each match."
  2968. (let ((outbuf " *SQL-Redirect-values*")
  2969. (results nil))
  2970. (sql-redirect sqlbuf command outbuf nil)
  2971. (with-current-buffer outbuf
  2972. (while (re-search-forward regexp nil t)
  2973. (push
  2974. (cond
  2975. ;; no groups-return all of them
  2976. ((null regexp-groups)
  2977. (let ((i (/ (length (match-data)) 2))
  2978. (r nil))
  2979. (while (> i 0)
  2980. (setq i (1- i))
  2981. (push (match-string i) r))
  2982. r))
  2983. ;; one group specified
  2984. ((numberp regexp-groups)
  2985. (match-string regexp-groups))
  2986. ;; list of numbers; return the specified matches only
  2987. ((consp regexp-groups)
  2988. (mapcar (lambda (c)
  2989. (cond
  2990. ((numberp c) (match-string c))
  2991. ((stringp c) (match-substitute-replacement c))
  2992. (t (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s" c))))
  2993. regexp-groups))
  2994. ;; String is specified; return replacement string
  2995. ((stringp regexp-groups)
  2996. (match-substitute-replacement regexp-groups))
  2997. (t
  2998. (error "sql-redirect-value: unknown REGEXP-GROUPS value - %s"
  2999. regexp-groups)))
  3000. results)))
  3001. (when sql-debug-redirect
  3002. (message ">>SQL> = %S" (reverse results)))
  3003. (nreverse results)))
  3004. (defun sql-execute (sqlbuf outbuf command enhanced arg)
  3005. "Executes a command in a SQL interactive buffer and captures the output.
  3006. The commands are run in SQLBUF and the output saved in OUTBUF.
  3007. COMMAND must be a string, a function or a list of such elements.
  3008. Functions are called with SQLBUF, OUTBUF and ARG as parameters;
  3009. strings are formatted with ARG and executed.
  3010. If the results are empty the OUTBUF is deleted, otherwise the
  3011. buffer is popped into a view window. "
  3012. (mapc
  3013. (lambda (c)
  3014. (cond
  3015. ((stringp c)
  3016. (sql-redirect sqlbuf (if arg (format c arg) c) outbuf) t)
  3017. ((functionp c)
  3018. (apply c sqlbuf outbuf enhanced arg nil))
  3019. (t (error "Unknown sql-execute item %s" c))))
  3020. (if (consp command) command (cons command nil)))
  3021. (setq outbuf (get-buffer outbuf))
  3022. (if (zerop (buffer-size outbuf))
  3023. (kill-buffer outbuf)
  3024. (let ((one-win (eq (selected-window)
  3025. (get-lru-window))))
  3026. (with-current-buffer outbuf
  3027. (set-buffer-modified-p nil)
  3028. (setq view-read-only t))
  3029. (view-buffer-other-window outbuf)
  3030. (when one-win
  3031. (shrink-window-if-larger-than-buffer)))))
  3032. (defun sql-execute-feature (sqlbuf outbuf feature enhanced arg)
  3033. "List objects or details in a separate display buffer."
  3034. (let (command)
  3035. (with-current-buffer sqlbuf
  3036. (setq command (sql-get-product-feature sql-product feature)))
  3037. (unless command
  3038. (error "%s does not support %s" sql-product feature))
  3039. (when (consp command)
  3040. (setq command (if enhanced
  3041. (cdr command)
  3042. (car command))))
  3043. (sql-execute sqlbuf outbuf command enhanced arg)))
  3044. (defvar sql-completion-object nil
  3045. "A list of database objects used for completion.
  3046. The list is maintained in SQL interactive buffers.")
  3047. (defvar sql-completion-column nil
  3048. "A list of column names used for completion.
  3049. The list is maintained in SQL interactive buffers.")
  3050. (defun sql-build-completions-1 (schema completion-list feature)
  3051. "Generate a list of objects in the database for use as completions."
  3052. (let ((f (sql-get-product-feature sql-product feature)))
  3053. (when f
  3054. (set completion-list
  3055. (let (cl)
  3056. (dolist (e (append (symbol-value completion-list)
  3057. (apply f (current-buffer) (cons schema nil)))
  3058. cl)
  3059. (unless (member e cl) (setq cl (cons e cl))))
  3060. (sort cl (function string<)))))))
  3061. (defun sql-build-completions (schema)
  3062. "Generate a list of names in the database for use as completions."
  3063. (sql-build-completions-1 schema 'sql-completion-object :completion-object)
  3064. (sql-build-completions-1 schema 'sql-completion-column :completion-column))
  3065. (defvar sql-completion-sqlbuf nil)
  3066. (defun sql-try-completion (string collection &optional predicate)
  3067. (when sql-completion-sqlbuf
  3068. (with-current-buffer sql-completion-sqlbuf
  3069. (let ((schema (and (string-match "\\`\\(\\sw\\(:?\\sw\\|\\s_\\)*\\)[.]" string)
  3070. (downcase (match-string 1 string)))))
  3071. ;; If we haven't loaded any object name yet, load local schema
  3072. (unless sql-completion-object
  3073. (sql-build-completions nil))
  3074. ;; If they want another schema, load it if we haven't yet
  3075. (when schema
  3076. (let ((schema-dot (concat schema "."))
  3077. (schema-len (1+ (length schema)))
  3078. (names sql-completion-object)
  3079. has-schema)
  3080. (while (and (not has-schema) names)
  3081. (setq has-schema (and
  3082. (>= (length (car names)) schema-len)
  3083. (string= schema-dot
  3084. (downcase (substring (car names)
  3085. 0 schema-len))))
  3086. names (cdr names)))
  3087. (unless has-schema
  3088. (sql-build-completions schema)))))
  3089. ;; Try to find the completion
  3090. (cond
  3091. ((not predicate)
  3092. (try-completion string sql-completion-object))
  3093. ((eq predicate t)
  3094. (all-completions string sql-completion-object))
  3095. ((eq predicate 'lambda)
  3096. (test-completion string sql-completion-object))
  3097. ((eq (car predicate) 'boundaries)
  3098. (completion-boundaries string sql-completion-object nil (cdr predicate)))))))
  3099. (defun sql-read-table-name (prompt)
  3100. "Read the name of a database table."
  3101. (let* ((tname
  3102. (and (buffer-local-value 'sql-contains-names (current-buffer))
  3103. (thing-at-point-looking-at
  3104. (concat "\\_<\\sw\\(:?\\sw\\|\\s_\\)*"
  3105. "\\(?:[.]+\\sw\\(?:\\sw\\|\\s_\\)*\\)*\\_>"))
  3106. (buffer-substring-no-properties (match-beginning 0)
  3107. (match-end 0))))
  3108. (sql-completion-sqlbuf (sql-find-sqli-buffer))
  3109. (product (with-current-buffer sql-completion-sqlbuf sql-product))
  3110. (completion-ignore-case t))
  3111. (if (sql-get-product-feature product :completion-object)
  3112. (completing-read prompt (function sql-try-completion)
  3113. nil nil tname)
  3114. (read-from-minibuffer prompt tname))))
  3115. (defun sql-list-all (&optional enhanced)
  3116. "List all database objects.
  3117. With optional prefix argument ENHANCED, displays additional
  3118. details or extends the listing to include other schemas objects."
  3119. (interactive "P")
  3120. (let ((sqlbuf (sql-find-sqli-buffer)))
  3121. (unless sqlbuf
  3122. (error "No SQL interactive buffer found"))
  3123. (sql-execute-feature sqlbuf "*List All*" :list-all enhanced nil)
  3124. (with-current-buffer sqlbuf
  3125. ;; Contains the name of database objects
  3126. (set (make-local-variable 'sql-contains-names) t)
  3127. (set (make-local-variable 'sql-buffer) sqlbuf))))
  3128. (defun sql-list-table (name &optional enhanced)
  3129. "List the details of a database table named NAME.
  3130. Displays the columns in the relation. With optional prefix argument
  3131. ENHANCED, displays additional details about each column."
  3132. (interactive
  3133. (list (sql-read-table-name "Table name: ")
  3134. current-prefix-arg))
  3135. (let ((sqlbuf (sql-find-sqli-buffer)))
  3136. (unless sqlbuf
  3137. (error "No SQL interactive buffer found"))
  3138. (unless name
  3139. (error "No table name specified"))
  3140. (sql-execute-feature sqlbuf (format "*List %s*" name)
  3141. :list-table enhanced name)))
  3142. ;;; SQL mode -- uses SQL interactive mode
  3143. ;;;###autoload
  3144. (define-derived-mode sql-mode prog-mode "SQL"
  3145. "Major mode to edit SQL.
  3146. You can send SQL statements to the SQLi buffer using
  3147. \\[sql-send-region]. Such a buffer must exist before you can do this.
  3148. See `sql-help' on how to create SQLi buffers.
  3149. \\{sql-mode-map}
  3150. Customization: Entry to this mode runs the `sql-mode-hook'.
  3151. When you put a buffer in SQL mode, the buffer stores the last SQLi
  3152. buffer created as its destination in the variable `sql-buffer'. This
  3153. will be the buffer \\[sql-send-region] sends the region to. If this
  3154. SQLi buffer is killed, \\[sql-send-region] is no longer able to
  3155. determine where the strings should be sent to. You can set the
  3156. value of `sql-buffer' using \\[sql-set-sqli-buffer].
  3157. For information on how to create multiple SQLi buffers, see
  3158. `sql-interactive-mode'.
  3159. Note that SQL doesn't have an escape character unless you specify
  3160. one. If you specify backslash as escape character in SQL,
  3161. you must tell Emacs. Here's how to do that in your `~/.emacs' file:
  3162. \(add-hook 'sql-mode-hook
  3163. (lambda ()
  3164. (modify-syntax-entry ?\\\\ \".\" sql-mode-syntax-table)))"
  3165. :abbrev-table sql-mode-abbrev-table
  3166. (if sql-mode-menu
  3167. (easy-menu-add sql-mode-menu)); XEmacs
  3168. (set (make-local-variable 'comment-start) "--")
  3169. ;; Make each buffer in sql-mode remember the "current" SQLi buffer.
  3170. (make-local-variable 'sql-buffer)
  3171. ;; Add imenu support for sql-mode. Note that imenu-generic-expression
  3172. ;; is buffer-local, so we don't need a local-variable for it. SQL is
  3173. ;; case-insensitive, that's why we have to set imenu-case-fold-search.
  3174. (setq imenu-generic-expression sql-imenu-generic-expression
  3175. imenu-case-fold-search t)
  3176. ;; Make `sql-send-paragraph' work on paragraphs that contain indented
  3177. ;; lines.
  3178. (set (make-local-variable 'paragraph-separate) "[\f]*$")
  3179. (set (make-local-variable 'paragraph-start) "[\n\f]")
  3180. ;; Abbrevs
  3181. (setq abbrev-all-caps 1)
  3182. ;; Contains the name of database objects
  3183. (set (make-local-variable 'sql-contains-names) t)
  3184. ;; Catch changes to sql-product and highlight accordingly
  3185. (add-hook 'hack-local-variables-hook 'sql-highlight-product t t))
  3186. ;;; SQL interactive mode
  3187. (put 'sql-interactive-mode 'mode-class 'special)
  3188. (defun sql-interactive-mode ()
  3189. "Major mode to use a SQL interpreter interactively.
  3190. Do not call this function by yourself. The environment must be
  3191. initialized by an entry function specific for the SQL interpreter.
  3192. See `sql-help' for a list of available entry functions.
  3193. \\[comint-send-input] after the end of the process' output sends the
  3194. text from the end of process to the end of the current line.
  3195. \\[comint-send-input] before end of process output copies the current
  3196. line minus the prompt to the end of the buffer and sends it.
  3197. \\[comint-copy-old-input] just copies the current line.
  3198. Use \\[sql-accumulate-and-indent] to enter multi-line statements.
  3199. If you want to make multiple SQL buffers, rename the `*SQL*' buffer
  3200. using \\[rename-buffer] or \\[rename-uniquely] and start a new process.
  3201. See `sql-help' for a list of available entry functions. The last buffer
  3202. created by such an entry function is the current SQLi buffer. SQL
  3203. buffers will send strings to the SQLi buffer current at the time of
  3204. their creation. See `sql-mode' for details.
  3205. Sample session using two connections:
  3206. 1. Create first SQLi buffer by calling an entry function.
  3207. 2. Rename buffer \"*SQL*\" to \"*Connection 1*\".
  3208. 3. Create a SQL buffer \"test1.sql\".
  3209. 4. Create second SQLi buffer by calling an entry function.
  3210. 5. Rename buffer \"*SQL*\" to \"*Connection 2*\".
  3211. 6. Create a SQL buffer \"test2.sql\".
  3212. Now \\[sql-send-region] in buffer \"test1.sql\" will send the region to
  3213. buffer \"*Connection 1*\", \\[sql-send-region] in buffer \"test2.sql\"
  3214. will send the region to buffer \"*Connection 2*\".
  3215. If you accidentally suspend your process, use \\[comint-continue-subjob]
  3216. to continue it. On some operating systems, this will not work because
  3217. the signals are not supported.
  3218. \\{sql-interactive-mode-map}
  3219. Customization: Entry to this mode runs the hooks on `comint-mode-hook'
  3220. and `sql-interactive-mode-hook' (in that order). Before each input, the
  3221. hooks on `comint-input-filter-functions' are run. After each SQL
  3222. interpreter output, the hooks on `comint-output-filter-functions' are
  3223. run.
  3224. Variable `sql-input-ring-file-name' controls the initialization of the
  3225. input ring history.
  3226. Variables `comint-output-filter-functions', a hook, and
  3227. `comint-scroll-to-bottom-on-input' and
  3228. `comint-scroll-to-bottom-on-output' control whether input and output
  3229. cause the window to scroll to the end of the buffer.
  3230. If you want to make SQL buffers limited in length, add the function
  3231. `comint-truncate-buffer' to `comint-output-filter-functions'.
  3232. Here is an example for your .emacs file. It keeps the SQLi buffer a
  3233. certain length.
  3234. \(add-hook 'sql-interactive-mode-hook
  3235. \(function (lambda ()
  3236. \(setq comint-output-filter-functions 'comint-truncate-buffer))))
  3237. Here is another example. It will always put point back to the statement
  3238. you entered, right above the output it created.
  3239. \(setq comint-output-filter-functions
  3240. \(function (lambda (STR) (comint-show-output))))"
  3241. (delay-mode-hooks (comint-mode))
  3242. ;; Get the `sql-product' for this interactive session.
  3243. (set (make-local-variable 'sql-product)
  3244. (or sql-interactive-product
  3245. sql-product))
  3246. ;; Setup the mode.
  3247. (setq major-mode 'sql-interactive-mode)
  3248. (setq mode-name
  3249. (concat "SQLi[" (or (sql-get-product-feature sql-product :name)
  3250. (symbol-name sql-product)) "]"))
  3251. (use-local-map sql-interactive-mode-map)
  3252. (if sql-interactive-mode-menu
  3253. (easy-menu-add sql-interactive-mode-menu)) ; XEmacs
  3254. (set-syntax-table sql-mode-syntax-table)
  3255. ;; Note that making KEYWORDS-ONLY nil will cause havoc if you try
  3256. ;; SELECT 'x' FROM DUAL with SQL*Plus, because the title of the column
  3257. ;; will have just one quote. Therefore syntactic highlighting is
  3258. ;; disabled for interactive buffers. No imenu support.
  3259. (sql-product-font-lock t nil)
  3260. ;; Enable commenting and uncommenting of the region.
  3261. (set (make-local-variable 'comment-start) "--")
  3262. ;; Abbreviation table init and case-insensitive. It is not activated
  3263. ;; by default.
  3264. (setq local-abbrev-table sql-mode-abbrev-table)
  3265. (setq abbrev-all-caps 1)
  3266. ;; Exiting the process will call sql-stop.
  3267. (set-process-sentinel (get-buffer-process (current-buffer)) 'sql-stop)
  3268. ;; Save the connection and login params
  3269. (set (make-local-variable 'sql-user) sql-user)
  3270. (set (make-local-variable 'sql-database) sql-database)
  3271. (set (make-local-variable 'sql-server) sql-server)
  3272. (set (make-local-variable 'sql-port) sql-port)
  3273. (set (make-local-variable 'sql-connection) sql-connection)
  3274. (setq-default sql-connection nil)
  3275. ;; Contains the name of database objects
  3276. (set (make-local-variable 'sql-contains-names) t)
  3277. ;; Keep track of existing object names
  3278. (set (make-local-variable 'sql-completion-object) nil)
  3279. (set (make-local-variable 'sql-completion-column) nil)
  3280. ;; Create a useful name for renaming this buffer later.
  3281. (set (make-local-variable 'sql-alternate-buffer-name)
  3282. (sql-make-alternate-buffer-name))
  3283. ;; User stuff. Initialize before the hook.
  3284. (set (make-local-variable 'sql-prompt-regexp)
  3285. (sql-get-product-feature sql-product :prompt-regexp))
  3286. (set (make-local-variable 'sql-prompt-length)
  3287. (sql-get-product-feature sql-product :prompt-length))
  3288. (set (make-local-variable 'sql-prompt-cont-regexp)
  3289. (sql-get-product-feature sql-product :prompt-cont-regexp))
  3290. (make-local-variable 'sql-output-newline-count)
  3291. (make-local-variable 'sql-preoutput-hold)
  3292. (make-local-variable 'sql-output-by-send)
  3293. (add-hook 'comint-preoutput-filter-functions
  3294. 'sql-interactive-remove-continuation-prompt nil t)
  3295. (make-local-variable 'sql-input-ring-separator)
  3296. (make-local-variable 'sql-input-ring-file-name)
  3297. ;; Run the mode hook (along with comint's hooks).
  3298. (run-mode-hooks 'sql-interactive-mode-hook)
  3299. ;; Set comint based on user overrides.
  3300. (setq comint-prompt-regexp
  3301. (if sql-prompt-cont-regexp
  3302. (concat "\\(" sql-prompt-regexp
  3303. "\\|" sql-prompt-cont-regexp "\\)")
  3304. sql-prompt-regexp))
  3305. (setq left-margin sql-prompt-length)
  3306. ;; Install input sender
  3307. (set (make-local-variable 'comint-input-sender) 'sql-input-sender)
  3308. ;; People wanting a different history file for each
  3309. ;; buffer/process/client/whatever can change separator and file-name
  3310. ;; on the sql-interactive-mode-hook.
  3311. (setq comint-input-ring-separator sql-input-ring-separator
  3312. comint-input-ring-file-name sql-input-ring-file-name)
  3313. ;; Calling the hook before calling comint-read-input-ring allows users
  3314. ;; to set comint-input-ring-file-name in sql-interactive-mode-hook.
  3315. (comint-read-input-ring t))
  3316. (defun sql-stop (process event)
  3317. "Called when the SQL process is stopped.
  3318. Writes the input history to a history file using
  3319. `comint-write-input-ring' and inserts a short message in the SQL buffer.
  3320. This function is a sentinel watching the SQL interpreter process.
  3321. Sentinels will always get the two parameters PROCESS and EVENT."
  3322. (comint-write-input-ring)
  3323. (if (and (eq (current-buffer) sql-buffer)
  3324. (not buffer-read-only))
  3325. (insert (format "\nProcess %s %s\n" process event))
  3326. (message "Process %s %s" process event)))
  3327. ;;; Connection handling
  3328. (defun sql-read-connection (prompt &optional initial default)
  3329. "Read a connection name."
  3330. (let ((completion-ignore-case t))
  3331. (completing-read prompt
  3332. (mapcar (lambda (c) (car c))
  3333. sql-connection-alist)
  3334. nil t initial 'sql-connection-history default)))
  3335. ;;;###autoload
  3336. (defun sql-connect (connection &optional new-name)
  3337. "Connect to an interactive session using CONNECTION settings.
  3338. See `sql-connection-alist' to see how to define connections and
  3339. their settings.
  3340. The user will not be prompted for any login parameters if a value
  3341. is specified in the connection settings."
  3342. ;; Prompt for the connection from those defined in the alist
  3343. (interactive
  3344. (if sql-connection-alist
  3345. (list (sql-read-connection "Connection: " nil '(nil))
  3346. current-prefix-arg)
  3347. nil))
  3348. ;; Are there connections defined
  3349. (if sql-connection-alist
  3350. ;; Was one selected
  3351. (when connection
  3352. ;; Get connection settings
  3353. (let ((connect-set (assoc connection sql-connection-alist)))
  3354. ;; Settings are defined
  3355. (if connect-set
  3356. ;; Set the desired parameters
  3357. (let (param-var login-params set-params rem-params)
  3358. ;; :sqli-login params variable
  3359. (setq param-var
  3360. (sql-get-product-feature sql-product :sqli-login nil t))
  3361. ;; :sqli-login params value
  3362. (setq login-params
  3363. (sql-get-product-feature sql-product :sqli-login))
  3364. ;; Params in the connection
  3365. (setq set-params
  3366. (mapcar
  3367. (lambda (v)
  3368. (cond
  3369. ((eq (car v) 'sql-user) 'user)
  3370. ((eq (car v) 'sql-password) 'password)
  3371. ((eq (car v) 'sql-server) 'server)
  3372. ((eq (car v) 'sql-database) 'database)
  3373. ((eq (car v) 'sql-port) 'port)
  3374. (t (car v))))
  3375. (cdr connect-set)))
  3376. ;; the remaining params (w/o the connection params)
  3377. (setq rem-params
  3378. (sql-for-each-login login-params
  3379. (lambda (token plist)
  3380. (unless (member token set-params)
  3381. (if plist (cons token plist) token)))))
  3382. ;; Set the parameters and start the interactive session
  3383. (mapc
  3384. (lambda (vv)
  3385. (set-default (car vv) (eval (cadr vv))))
  3386. (cdr connect-set))
  3387. (setq-default sql-connection connection)
  3388. ;; Start the SQLi session with revised list of login parameters
  3389. (eval `(let ((,param-var ',rem-params))
  3390. (sql-product-interactive sql-product new-name))))
  3391. (message "SQL Connection <%s> does not exist" connection)
  3392. nil)))
  3393. (message "No SQL Connections defined")
  3394. nil))
  3395. (defun sql-save-connection (name)
  3396. "Captures the connection information of the current SQLi session.
  3397. The information is appended to `sql-connection-alist' and
  3398. optionally is saved to the user's init file."
  3399. (interactive "sNew connection name: ")
  3400. (unless (derived-mode-p 'sql-interactive-mode)
  3401. (error "Not in a SQL interactive mode!"))
  3402. ;; Capture the buffer local settings
  3403. (let* ((buf (current-buffer))
  3404. (connection (buffer-local-value 'sql-connection buf))
  3405. (product (buffer-local-value 'sql-product buf))
  3406. (user (buffer-local-value 'sql-user buf))
  3407. (database (buffer-local-value 'sql-database buf))
  3408. (server (buffer-local-value 'sql-server buf))
  3409. (port (buffer-local-value 'sql-port buf)))
  3410. (if connection
  3411. (message "This session was started by a connection; it's already been saved.")
  3412. (let ((login (sql-get-product-feature product :sqli-login))
  3413. (alist sql-connection-alist)
  3414. connect)
  3415. ;; Remove the existing connection if the user says so
  3416. (when (and (assoc name alist)
  3417. (yes-or-no-p (format "Replace connection definition <%s>? " name)))
  3418. (setq alist (assq-delete-all name alist)))
  3419. ;; Add the new connection if it doesn't exist
  3420. (if (assoc name alist)
  3421. (message "Connection <%s> already exists" name)
  3422. (setq connect
  3423. (append (list name)
  3424. (sql-for-each-login
  3425. `(product ,@login)
  3426. (lambda (token _plist)
  3427. (cond
  3428. ((eq token 'product) `(sql-product ',product))
  3429. ((eq token 'user) `(sql-user ,user))
  3430. ((eq token 'database) `(sql-database ,database))
  3431. ((eq token 'server) `(sql-server ,server))
  3432. ((eq token 'port) `(sql-port ,port)))))))
  3433. (setq alist (append alist (list connect)))
  3434. ;; confirm whether we want to save the connections
  3435. (if (yes-or-no-p "Save the connections for future sessions? ")
  3436. (customize-save-variable 'sql-connection-alist alist)
  3437. (customize-set-variable 'sql-connection-alist alist)))))))
  3438. (defun sql-connection-menu-filter (tail)
  3439. "Generates menu entries for using each connection."
  3440. (append
  3441. (mapcar
  3442. (lambda (conn)
  3443. (vector
  3444. (format "Connection <%s>\t%s" (car conn)
  3445. (let ((sql-user "") (sql-database "")
  3446. (sql-server "") (sql-port 0))
  3447. (eval `(let ,(cdr conn) (sql-make-alternate-buffer-name)))))
  3448. (list 'sql-connect (car conn))
  3449. t))
  3450. sql-connection-alist)
  3451. tail))
  3452. ;;; Entry functions for different SQL interpreters.
  3453. ;;;###autoload
  3454. (defun sql-product-interactive (&optional product new-name)
  3455. "Run PRODUCT interpreter as an inferior process.
  3456. If buffer `*SQL*' exists but no process is running, make a new process.
  3457. If buffer exists and a process is running, just switch to buffer `*SQL*'.
  3458. To specify the SQL product, prefix the call with
  3459. \\[universal-argument]. To set the buffer name as well, prefix
  3460. the call to \\[sql-product-interactive] with
  3461. \\[universal-argument] \\[universal-argument].
  3462. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3463. (interactive "P")
  3464. ;; Handle universal arguments if specified
  3465. (when (not (or executing-kbd-macro noninteractive))
  3466. (when (and (consp product)
  3467. (not (cdr product))
  3468. (numberp (car product)))
  3469. (when (>= (prefix-numeric-value product) 16)
  3470. (when (not new-name)
  3471. (setq new-name '(4)))
  3472. (setq product '(4)))))
  3473. ;; Get the value of product that we need
  3474. (setq product
  3475. (cond
  3476. ((= (prefix-numeric-value product) 4) ; C-u, prompt for product
  3477. (sql-read-product "SQL product: " sql-product))
  3478. ((and product ; Product specified
  3479. (symbolp product)) product)
  3480. (t sql-product))) ; Default to sql-product
  3481. ;; If we have a product and it has a interactive mode
  3482. (if product
  3483. (when (sql-get-product-feature product :sqli-comint-func)
  3484. ;; If no new name specified, try to pop to an active SQL
  3485. ;; interactive for the same product
  3486. (let ((buf (sql-find-sqli-buffer product sql-connection)))
  3487. (if (and (not new-name) buf)
  3488. (pop-to-buffer buf)
  3489. ;; We have a new name or sql-buffer doesn't exist or match
  3490. ;; Start by remembering where we start
  3491. (let ((start-buffer (current-buffer))
  3492. new-sqli-buffer)
  3493. ;; Get credentials.
  3494. (apply 'sql-get-login (sql-get-product-feature product :sqli-login))
  3495. ;; Connect to database.
  3496. (message "Login...")
  3497. (let ((sql-user (default-value 'sql-user))
  3498. (sql-password (default-value 'sql-password))
  3499. (sql-server (default-value 'sql-server))
  3500. (sql-database (default-value 'sql-database))
  3501. (sql-port (default-value 'sql-port)))
  3502. (funcall (sql-get-product-feature product :sqli-comint-func)
  3503. product
  3504. (sql-get-product-feature product :sqli-options)))
  3505. ;; Set SQLi mode.
  3506. (let ((sql-interactive-product product))
  3507. (sql-interactive-mode))
  3508. ;; Set the new buffer name
  3509. (setq new-sqli-buffer (current-buffer))
  3510. (when new-name
  3511. (sql-rename-buffer new-name))
  3512. (set (make-local-variable 'sql-buffer)
  3513. (buffer-name new-sqli-buffer))
  3514. ;; Set `sql-buffer' in the start buffer
  3515. (with-current-buffer start-buffer
  3516. (when (derived-mode-p 'sql-mode)
  3517. (setq sql-buffer (buffer-name new-sqli-buffer))
  3518. (run-hooks 'sql-set-sqli-hook)))
  3519. ;; All done.
  3520. (message "Login...done")
  3521. (run-hooks 'sql-login-hook)
  3522. (pop-to-buffer new-sqli-buffer)))))
  3523. (message "No default SQL product defined. Set `sql-product'.")))
  3524. (defun sql-comint (product params)
  3525. "Set up a comint buffer to run the SQL processor.
  3526. PRODUCT is the SQL product. PARAMS is a list of strings which are
  3527. passed as command line arguments."
  3528. (let ((program (sql-get-product-feature product :sqli-program))
  3529. (buf-name "SQL"))
  3530. ;; make sure we can find the program
  3531. (unless (executable-find program)
  3532. (error "Unable to locate SQL program \'%s\'" program))
  3533. ;; Make sure buffer name is unique
  3534. (when (sql-buffer-live-p (format "*%s*" buf-name))
  3535. (setq buf-name (format "SQL-%s" product))
  3536. (when (sql-buffer-live-p (format "*%s*" buf-name))
  3537. (let ((i 1))
  3538. (while (sql-buffer-live-p
  3539. (format "*%s*"
  3540. (setq buf-name (format "SQL-%s%d" product i))))
  3541. (setq i (1+ i))))))
  3542. (set-buffer
  3543. (apply 'make-comint buf-name program nil params))))
  3544. ;;;###autoload
  3545. (defun sql-oracle (&optional buffer)
  3546. "Run sqlplus by Oracle as an inferior process.
  3547. If buffer `*SQL*' exists but no process is running, make a new process.
  3548. If buffer exists and a process is running, just switch to buffer
  3549. `*SQL*'.
  3550. Interpreter used comes from variable `sql-oracle-program'. Login uses
  3551. the variables `sql-user', `sql-password', and `sql-database' as
  3552. defaults, if set. Additional command line parameters can be stored in
  3553. the list `sql-oracle-options'.
  3554. The buffer is put in SQL interactive mode, giving commands for sending
  3555. input. See `sql-interactive-mode'.
  3556. To set the buffer name directly, use \\[universal-argument]
  3557. before \\[sql-oracle]. Once session has started,
  3558. \\[sql-rename-buffer] can be called separately to rename the
  3559. buffer.
  3560. To specify a coding system for converting non-ASCII characters
  3561. in the input and output to the process, use \\[universal-coding-system-argument]
  3562. before \\[sql-oracle]. You can also specify this with \\[set-buffer-process-coding-system]
  3563. in the SQL buffer, after you start the process.
  3564. The default comes from `process-coding-system-alist' and
  3565. `default-process-coding-system'.
  3566. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3567. (interactive "P")
  3568. (sql-product-interactive 'oracle buffer))
  3569. (defun sql-comint-oracle (product options)
  3570. "Create comint buffer and connect to Oracle."
  3571. ;; Produce user/password@database construct. Password without user
  3572. ;; is meaningless; database without user/password is meaningless,
  3573. ;; because "@param" will ask sqlplus to interpret the script
  3574. ;; "param".
  3575. (let ((parameter nil))
  3576. (if (not (string= "" sql-user))
  3577. (if (not (string= "" sql-password))
  3578. (setq parameter (concat sql-user "/" sql-password))
  3579. (setq parameter sql-user)))
  3580. (if (and parameter (not (string= "" sql-database)))
  3581. (setq parameter (concat parameter "@" sql-database)))
  3582. (if parameter
  3583. (setq parameter (nconc (list parameter) options))
  3584. (setq parameter options))
  3585. (sql-comint product parameter)))
  3586. (defun sql-oracle-save-settings (sqlbuf)
  3587. "Saves most SQL*Plus settings so they may be reset by \\[sql-redirect]."
  3588. ;; Note: does not capture the following settings:
  3589. ;;
  3590. ;; APPINFO
  3591. ;; BTITLE
  3592. ;; COMPATIBILITY
  3593. ;; COPYTYPECHECK
  3594. ;; MARKUP
  3595. ;; RELEASE
  3596. ;; REPFOOTER
  3597. ;; REPHEADER
  3598. ;; SQLPLUSCOMPATIBILITY
  3599. ;; TTITLE
  3600. ;; USER
  3601. ;;
  3602. (append
  3603. ;; (apply 'concat (append
  3604. ;; '("SET")
  3605. ;; option value...
  3606. (sql-redirect-value
  3607. sqlbuf
  3608. (concat "SHOW ARRAYSIZE AUTOCOMMIT AUTOPRINT AUTORECOVERY AUTOTRACE"
  3609. " CMDSEP COLSEP COPYCOMMIT DESCRIBE ECHO EDITFILE EMBEDDED"
  3610. " ESCAPE FLAGGER FLUSH HEADING INSTANCE LINESIZE LNO LOBOFFSET"
  3611. " LOGSOURCE LONG LONGCHUNKSIZE NEWPAGE NULL NUMFORMAT NUMWIDTH"
  3612. " PAGESIZE PAUSE PNO RECSEP SERVEROUTPUT SHIFTINOUT SHOWMODE"
  3613. " SPOOL SQLBLANKLINES SQLCASE SQLCODE SQLCONTINUE SQLNUMBER"
  3614. " SQLPROMPT SUFFIX TAB TERMOUT TIMING TRIMOUT TRIMSPOOL VERIFY")
  3615. "^.+$"
  3616. "SET \\&")
  3617. ;; option "c" (hex xx)
  3618. (sql-redirect-value
  3619. sqlbuf
  3620. (concat "SHOW BLOCKTERMINATOR CONCAT DEFINE SQLPREFIX SQLTERMINATOR"
  3621. " UNDERLINE HEADSEP RECSEPCHAR")
  3622. "^\\(.+\\) (hex ..)$"
  3623. "SET \\1")
  3624. ;; FEEDBACK ON for 99 or more rows
  3625. ;; feedback OFF
  3626. (sql-redirect-value
  3627. sqlbuf
  3628. "SHOW FEEDBACK"
  3629. "^\\(?:FEEDBACK ON for \\([[:digit:]]+\\) or more rows\\|feedback \\(OFF\\)\\)"
  3630. "SET FEEDBACK \\1\\2")
  3631. ;; wrap : lines will be wrapped
  3632. ;; wrap : lines will be truncated
  3633. (list (concat "SET WRAP "
  3634. (if (string=
  3635. (car (sql-redirect-value
  3636. sqlbuf
  3637. "SHOW WRAP"
  3638. "^wrap : lines will be \\(wrapped\\|truncated\\)" 1))
  3639. "wrapped")
  3640. "ON" "OFF")))))
  3641. (defun sql-oracle-restore-settings (sqlbuf saved-settings)
  3642. "Restore the SQL*Plus settings in SAVED-SETTINGS."
  3643. ;; Remove any settings that haven't changed
  3644. (mapc
  3645. (lambda (one-cur-setting)
  3646. (setq saved-settings (delete one-cur-setting saved-settings)))
  3647. (sql-oracle-save-settings sqlbuf))
  3648. ;; Restore the changed settings
  3649. (sql-redirect sqlbuf saved-settings))
  3650. (defun sql-oracle-list-all (sqlbuf outbuf enhanced table-name)
  3651. ;; Query from USER_OBJECTS or ALL_OBJECTS
  3652. (let ((settings (sql-oracle-save-settings sqlbuf))
  3653. (simple-sql
  3654. (concat
  3655. "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
  3656. ", x.object_name AS SQL_EL_NAME "
  3657. "FROM user_objects x "
  3658. "WHERE x.object_type NOT LIKE '%% BODY' "
  3659. "ORDER BY 2, 1;"))
  3660. (enhanced-sql
  3661. (concat
  3662. "SELECT INITCAP(x.object_type) AS SQL_EL_TYPE "
  3663. ", x.owner ||'.'|| x.object_name AS SQL_EL_NAME "
  3664. "FROM all_objects x "
  3665. "WHERE x.object_type NOT LIKE '%% BODY' "
  3666. "AND x.owner <> 'SYS' "
  3667. "ORDER BY 2, 1;")))
  3668. (sql-redirect sqlbuf
  3669. (concat "SET LINESIZE 80 PAGESIZE 50000 TRIMOUT ON"
  3670. " TAB OFF TIMING OFF FEEDBACK OFF"))
  3671. (sql-redirect sqlbuf
  3672. (list "COLUMN SQL_EL_TYPE HEADING \"Type\" FORMAT A19"
  3673. "COLUMN SQL_EL_NAME HEADING \"Name\""
  3674. (format "COLUMN SQL_EL_NAME FORMAT A%d"
  3675. (if enhanced 60 35))))
  3676. (sql-redirect sqlbuf
  3677. (if enhanced enhanced-sql simple-sql)
  3678. outbuf)
  3679. (sql-redirect sqlbuf
  3680. '("COLUMN SQL_EL_NAME CLEAR"
  3681. "COLUMN SQL_EL_TYPE CLEAR"))
  3682. (sql-oracle-restore-settings sqlbuf settings)))
  3683. (defun sql-oracle-list-table (sqlbuf outbuf enhanced table-name)
  3684. "Implements :list-table under Oracle."
  3685. (let ((settings (sql-oracle-save-settings sqlbuf)))
  3686. (sql-redirect sqlbuf
  3687. (format
  3688. (concat "SET LINESIZE %d PAGESIZE 50000"
  3689. " DESCRIBE DEPTH 1 LINENUM OFF INDENT ON")
  3690. (max 65 (min 120 (window-width)))))
  3691. (sql-redirect sqlbuf (format "DESCRIBE %s" table-name)
  3692. outbuf)
  3693. (sql-oracle-restore-settings sqlbuf settings)))
  3694. (defcustom sql-oracle-completion-types '("FUNCTION" "PACKAGE" "PROCEDURE"
  3695. "SEQUENCE" "SYNONYM" "TABLE" "TRIGGER"
  3696. "TYPE" "VIEW")
  3697. "List of object types to include for completion under Oracle.
  3698. See the distinct values in ALL_OBJECTS.OBJECT_TYPE for possible values."
  3699. :version "24.1"
  3700. :type '(repeat string)
  3701. :group 'SQL)
  3702. (defun sql-oracle-completion-object (sqlbuf schema)
  3703. (sql-redirect-value
  3704. sqlbuf
  3705. (concat
  3706. "SELECT CHR(1)||"
  3707. (if schema
  3708. (format "owner||'.'||object_name AS o FROM all_objects WHERE owner = %s AND "
  3709. (sql-str-literal (upcase schema)))
  3710. "object_name AS o FROM user_objects WHERE ")
  3711. "temporary = 'N' AND generated = 'N' AND secondary = 'N' AND "
  3712. "object_type IN ("
  3713. (mapconcat (function sql-str-literal) sql-oracle-completion-types ",")
  3714. ");")
  3715. "^[\001]\\(.+\\)$" 1))
  3716. ;;;###autoload
  3717. (defun sql-sybase (&optional buffer)
  3718. "Run isql by Sybase as an inferior process.
  3719. If buffer `*SQL*' exists but no process is running, make a new process.
  3720. If buffer exists and a process is running, just switch to buffer
  3721. `*SQL*'.
  3722. Interpreter used comes from variable `sql-sybase-program'. Login uses
  3723. the variables `sql-server', `sql-user', `sql-password', and
  3724. `sql-database' as defaults, if set. Additional command line parameters
  3725. can be stored in the list `sql-sybase-options'.
  3726. The buffer is put in SQL interactive mode, giving commands for sending
  3727. input. See `sql-interactive-mode'.
  3728. To set the buffer name directly, use \\[universal-argument]
  3729. before \\[sql-sybase]. Once session has started,
  3730. \\[sql-rename-buffer] can be called separately to rename the
  3731. buffer.
  3732. To specify a coding system for converting non-ASCII characters
  3733. in the input and output to the process, use \\[universal-coding-system-argument]
  3734. before \\[sql-sybase]. You can also specify this with \\[set-buffer-process-coding-system]
  3735. in the SQL buffer, after you start the process.
  3736. The default comes from `process-coding-system-alist' and
  3737. `default-process-coding-system'.
  3738. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3739. (interactive "P")
  3740. (sql-product-interactive 'sybase buffer))
  3741. (defun sql-comint-sybase (product options)
  3742. "Create comint buffer and connect to Sybase."
  3743. ;; Put all parameters to the program (if defined) in a list and call
  3744. ;; make-comint.
  3745. (let ((params options))
  3746. (if (not (string= "" sql-server))
  3747. (setq params (append (list "-S" sql-server) params)))
  3748. (if (not (string= "" sql-database))
  3749. (setq params (append (list "-D" sql-database) params)))
  3750. (if (not (string= "" sql-password))
  3751. (setq params (append (list "-P" sql-password) params)))
  3752. (if (not (string= "" sql-user))
  3753. (setq params (append (list "-U" sql-user) params)))
  3754. (sql-comint product params)))
  3755. ;;;###autoload
  3756. (defun sql-informix (&optional buffer)
  3757. "Run dbaccess by Informix as an inferior process.
  3758. If buffer `*SQL*' exists but no process is running, make a new process.
  3759. If buffer exists and a process is running, just switch to buffer
  3760. `*SQL*'.
  3761. Interpreter used comes from variable `sql-informix-program'. Login uses
  3762. the variable `sql-database' as default, if set.
  3763. The buffer is put in SQL interactive mode, giving commands for sending
  3764. input. See `sql-interactive-mode'.
  3765. To set the buffer name directly, use \\[universal-argument]
  3766. before \\[sql-informix]. Once session has started,
  3767. \\[sql-rename-buffer] can be called separately to rename the
  3768. buffer.
  3769. To specify a coding system for converting non-ASCII characters
  3770. in the input and output to the process, use \\[universal-coding-system-argument]
  3771. before \\[sql-informix]. You can also specify this with \\[set-buffer-process-coding-system]
  3772. in the SQL buffer, after you start the process.
  3773. The default comes from `process-coding-system-alist' and
  3774. `default-process-coding-system'.
  3775. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3776. (interactive "P")
  3777. (sql-product-interactive 'informix buffer))
  3778. (defun sql-comint-informix (product options)
  3779. "Create comint buffer and connect to Informix."
  3780. ;; username and password are ignored.
  3781. (let ((db (if (string= "" sql-database)
  3782. "-"
  3783. (if (string= "" sql-server)
  3784. sql-database
  3785. (concat sql-database "@" sql-server)))))
  3786. (sql-comint product (append `(,db "-") options))))
  3787. ;;;###autoload
  3788. (defun sql-sqlite (&optional buffer)
  3789. "Run sqlite as an inferior process.
  3790. SQLite is free software.
  3791. If buffer `*SQL*' exists but no process is running, make a new process.
  3792. If buffer exists and a process is running, just switch to buffer
  3793. `*SQL*'.
  3794. Interpreter used comes from variable `sql-sqlite-program'. Login uses
  3795. the variables `sql-user', `sql-password', `sql-database', and
  3796. `sql-server' as defaults, if set. Additional command line parameters
  3797. can be stored in the list `sql-sqlite-options'.
  3798. The buffer is put in SQL interactive mode, giving commands for sending
  3799. input. See `sql-interactive-mode'.
  3800. To set the buffer name directly, use \\[universal-argument]
  3801. before \\[sql-sqlite]. Once session has started,
  3802. \\[sql-rename-buffer] can be called separately to rename the
  3803. buffer.
  3804. To specify a coding system for converting non-ASCII characters
  3805. in the input and output to the process, use \\[universal-coding-system-argument]
  3806. before \\[sql-sqlite]. You can also specify this with \\[set-buffer-process-coding-system]
  3807. in the SQL buffer, after you start the process.
  3808. The default comes from `process-coding-system-alist' and
  3809. `default-process-coding-system'.
  3810. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3811. (interactive "P")
  3812. (sql-product-interactive 'sqlite buffer))
  3813. (defun sql-comint-sqlite (product options)
  3814. "Create comint buffer and connect to SQLite."
  3815. ;; Put all parameters to the program (if defined) in a list and call
  3816. ;; make-comint.
  3817. (let ((params))
  3818. (if (not (string= "" sql-database))
  3819. (setq params (append (list (expand-file-name sql-database))
  3820. params)))
  3821. (setq params (append options params))
  3822. (sql-comint product params)))
  3823. (defun sql-sqlite-completion-object (sqlbuf schema)
  3824. (sql-redirect-value sqlbuf ".tables" "\\sw\\(?:\\sw\\|\\s_\\)*" 0))
  3825. ;;;###autoload
  3826. (defun sql-mysql (&optional buffer)
  3827. "Run mysql by TcX as an inferior process.
  3828. Mysql versions 3.23 and up are free software.
  3829. If buffer `*SQL*' exists but no process is running, make a new process.
  3830. If buffer exists and a process is running, just switch to buffer
  3831. `*SQL*'.
  3832. Interpreter used comes from variable `sql-mysql-program'. Login uses
  3833. the variables `sql-user', `sql-password', `sql-database', and
  3834. `sql-server' as defaults, if set. Additional command line parameters
  3835. can be stored in the list `sql-mysql-options'.
  3836. The buffer is put in SQL interactive mode, giving commands for sending
  3837. input. See `sql-interactive-mode'.
  3838. To set the buffer name directly, use \\[universal-argument]
  3839. before \\[sql-mysql]. Once session has started,
  3840. \\[sql-rename-buffer] can be called separately to rename the
  3841. buffer.
  3842. To specify a coding system for converting non-ASCII characters
  3843. in the input and output to the process, use \\[universal-coding-system-argument]
  3844. before \\[sql-mysql]. You can also specify this with \\[set-buffer-process-coding-system]
  3845. in the SQL buffer, after you start the process.
  3846. The default comes from `process-coding-system-alist' and
  3847. `default-process-coding-system'.
  3848. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3849. (interactive "P")
  3850. (sql-product-interactive 'mysql buffer))
  3851. (defun sql-comint-mysql (product options)
  3852. "Create comint buffer and connect to MySQL."
  3853. ;; Put all parameters to the program (if defined) in a list and call
  3854. ;; make-comint.
  3855. (let ((params))
  3856. (if (not (string= "" sql-database))
  3857. (setq params (append (list sql-database) params)))
  3858. (if (not (string= "" sql-server))
  3859. (setq params (append (list (concat "--host=" sql-server)) params)))
  3860. (if (not (= 0 sql-port))
  3861. (setq params (append (list (concat "--port=" (number-to-string sql-port))) params)))
  3862. (if (not (string= "" sql-password))
  3863. (setq params (append (list (concat "--password=" sql-password)) params)))
  3864. (if (not (string= "" sql-user))
  3865. (setq params (append (list (concat "--user=" sql-user)) params)))
  3866. (setq params (append options params))
  3867. (sql-comint product params)))
  3868. ;;;###autoload
  3869. (defun sql-solid (&optional buffer)
  3870. "Run solsql by Solid as an inferior process.
  3871. If buffer `*SQL*' exists but no process is running, make a new process.
  3872. If buffer exists and a process is running, just switch to buffer
  3873. `*SQL*'.
  3874. Interpreter used comes from variable `sql-solid-program'. Login uses
  3875. the variables `sql-user', `sql-password', and `sql-server' as
  3876. defaults, if set.
  3877. The buffer is put in SQL interactive mode, giving commands for sending
  3878. input. See `sql-interactive-mode'.
  3879. To set the buffer name directly, use \\[universal-argument]
  3880. before \\[sql-solid]. Once session has started,
  3881. \\[sql-rename-buffer] can be called separately to rename the
  3882. buffer.
  3883. To specify a coding system for converting non-ASCII characters
  3884. in the input and output to the process, use \\[universal-coding-system-argument]
  3885. before \\[sql-solid]. You can also specify this with \\[set-buffer-process-coding-system]
  3886. in the SQL buffer, after you start the process.
  3887. The default comes from `process-coding-system-alist' and
  3888. `default-process-coding-system'.
  3889. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3890. (interactive "P")
  3891. (sql-product-interactive 'solid buffer))
  3892. (defun sql-comint-solid (product options)
  3893. "Create comint buffer and connect to Solid."
  3894. ;; Put all parameters to the program (if defined) in a list and call
  3895. ;; make-comint.
  3896. (let ((params options))
  3897. ;; It only makes sense if both username and password are there.
  3898. (if (not (or (string= "" sql-user)
  3899. (string= "" sql-password)))
  3900. (setq params (append (list sql-user sql-password) params)))
  3901. (if (not (string= "" sql-server))
  3902. (setq params (append (list sql-server) params)))
  3903. (sql-comint product params)))
  3904. ;;;###autoload
  3905. (defun sql-ingres (&optional buffer)
  3906. "Run sql by Ingres as an inferior process.
  3907. If buffer `*SQL*' exists but no process is running, make a new process.
  3908. If buffer exists and a process is running, just switch to buffer
  3909. `*SQL*'.
  3910. Interpreter used comes from variable `sql-ingres-program'. Login uses
  3911. the variable `sql-database' as default, if set.
  3912. The buffer is put in SQL interactive mode, giving commands for sending
  3913. input. See `sql-interactive-mode'.
  3914. To set the buffer name directly, use \\[universal-argument]
  3915. before \\[sql-ingres]. Once session has started,
  3916. \\[sql-rename-buffer] can be called separately to rename the
  3917. buffer.
  3918. To specify a coding system for converting non-ASCII characters
  3919. in the input and output to the process, use \\[universal-coding-system-argument]
  3920. before \\[sql-ingres]. You can also specify this with \\[set-buffer-process-coding-system]
  3921. in the SQL buffer, after you start the process.
  3922. The default comes from `process-coding-system-alist' and
  3923. `default-process-coding-system'.
  3924. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3925. (interactive "P")
  3926. (sql-product-interactive 'ingres buffer))
  3927. (defun sql-comint-ingres (product options)
  3928. "Create comint buffer and connect to Ingres."
  3929. ;; username and password are ignored.
  3930. (sql-comint product
  3931. (append (if (string= "" sql-database)
  3932. nil
  3933. (list sql-database))
  3934. options)))
  3935. ;;;###autoload
  3936. (defun sql-ms (&optional buffer)
  3937. "Run osql by Microsoft as an inferior process.
  3938. If buffer `*SQL*' exists but no process is running, make a new process.
  3939. If buffer exists and a process is running, just switch to buffer
  3940. `*SQL*'.
  3941. Interpreter used comes from variable `sql-ms-program'. Login uses the
  3942. variables `sql-user', `sql-password', `sql-database', and `sql-server'
  3943. as defaults, if set. Additional command line parameters can be stored
  3944. in the list `sql-ms-options'.
  3945. The buffer is put in SQL interactive mode, giving commands for sending
  3946. input. See `sql-interactive-mode'.
  3947. To set the buffer name directly, use \\[universal-argument]
  3948. before \\[sql-ms]. Once session has started,
  3949. \\[sql-rename-buffer] can be called separately to rename the
  3950. buffer.
  3951. To specify a coding system for converting non-ASCII characters
  3952. in the input and output to the process, use \\[universal-coding-system-argument]
  3953. before \\[sql-ms]. You can also specify this with \\[set-buffer-process-coding-system]
  3954. in the SQL buffer, after you start the process.
  3955. The default comes from `process-coding-system-alist' and
  3956. `default-process-coding-system'.
  3957. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  3958. (interactive "P")
  3959. (sql-product-interactive 'ms buffer))
  3960. (defun sql-comint-ms (product options)
  3961. "Create comint buffer and connect to Microsoft SQL Server."
  3962. ;; Put all parameters to the program (if defined) in a list and call
  3963. ;; make-comint.
  3964. (let ((params options))
  3965. (if (not (string= "" sql-server))
  3966. (setq params (append (list "-S" sql-server) params)))
  3967. (if (not (string= "" sql-database))
  3968. (setq params (append (list "-d" sql-database) params)))
  3969. (if (not (string= "" sql-user))
  3970. (setq params (append (list "-U" sql-user) params)))
  3971. (if (not (string= "" sql-password))
  3972. (setq params (append (list "-P" sql-password) params))
  3973. (if (string= "" sql-user)
  3974. ;; if neither user nor password is provided, use system
  3975. ;; credentials.
  3976. (setq params (append (list "-E") params))
  3977. ;; If -P is passed to ISQL as the last argument without a
  3978. ;; password, it's considered null.
  3979. (setq params (append params (list "-P")))))
  3980. (sql-comint product params)))
  3981. ;;;###autoload
  3982. (defun sql-postgres (&optional buffer)
  3983. "Run psql by Postgres as an inferior process.
  3984. If buffer `*SQL*' exists but no process is running, make a new process.
  3985. If buffer exists and a process is running, just switch to buffer
  3986. `*SQL*'.
  3987. Interpreter used comes from variable `sql-postgres-program'. Login uses
  3988. the variables `sql-database' and `sql-server' as default, if set.
  3989. Additional command line parameters can be stored in the list
  3990. `sql-postgres-options'.
  3991. The buffer is put in SQL interactive mode, giving commands for sending
  3992. input. See `sql-interactive-mode'.
  3993. To set the buffer name directly, use \\[universal-argument]
  3994. before \\[sql-postgres]. Once session has started,
  3995. \\[sql-rename-buffer] can be called separately to rename the
  3996. buffer.
  3997. To specify a coding system for converting non-ASCII characters
  3998. in the input and output to the process, use \\[universal-coding-system-argument]
  3999. before \\[sql-postgres]. You can also specify this with \\[set-buffer-process-coding-system]
  4000. in the SQL buffer, after you start the process.
  4001. The default comes from `process-coding-system-alist' and
  4002. `default-process-coding-system'. If your output lines end with ^M,
  4003. your might try undecided-dos as a coding system. If this doesn't help,
  4004. Try to set `comint-output-filter-functions' like this:
  4005. \(setq comint-output-filter-functions (append comint-output-filter-functions
  4006. '(comint-strip-ctrl-m)))
  4007. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  4008. (interactive "P")
  4009. (sql-product-interactive 'postgres buffer))
  4010. (defun sql-comint-postgres (product options)
  4011. "Create comint buffer and connect to Postgres."
  4012. ;; username and password are ignored. Mark Stosberg suggest to add
  4013. ;; the database at the end. Jason Beegan suggest using --pset and
  4014. ;; pager=off instead of \\o|cat. The later was the solution by
  4015. ;; Gregor Zych. Jason's suggestion is the default value for
  4016. ;; sql-postgres-options.
  4017. (let ((params options))
  4018. (if (not (string= "" sql-database))
  4019. (setq params (append params (list sql-database))))
  4020. (if (not (string= "" sql-server))
  4021. (setq params (append (list "-h" sql-server) params)))
  4022. (if (not (string= "" sql-user))
  4023. (setq params (append (list "-U" sql-user) params)))
  4024. (if (not (= 0 sql-port))
  4025. (setq params (append (list "-p" (number-to-string sql-port)) params)))
  4026. (sql-comint product params)))
  4027. (defun sql-postgres-completion-object (sqlbuf schema)
  4028. (let (cl re fs a r)
  4029. (sql-redirect sqlbuf "\\t on")
  4030. (setq a (car (sql-redirect-value sqlbuf "\\a" "Output format is \\(.*\\)[.]$" 1)))
  4031. (when (string= a "aligned")
  4032. (sql-redirect sqlbuf "\\a"))
  4033. (setq fs (or (car (sql-redirect-value sqlbuf "\\f" "Field separator is \"\\(.\\)[.]$" 1)) "|"))
  4034. (setq re (concat "^\\([^" fs "]*\\)" fs "\\([^" fs "]*\\)" fs "[^" fs "]*" fs "[^" fs "]*$"))
  4035. (setq cl (if (not schema)
  4036. (sql-redirect-value sqlbuf "\\d" re '(1 2))
  4037. (append (sql-redirect-value sqlbuf (format "\\dt %s.*" schema) re '(1 2))
  4038. (sql-redirect-value sqlbuf (format "\\dv %s.*" schema) re '(1 2))
  4039. (sql-redirect-value sqlbuf (format "\\ds %s.*" schema) re '(1 2)))))
  4040. ;; Restore tuples and alignment to what they were
  4041. (sql-redirect sqlbuf "\\t off")
  4042. (when (not (string= a "aligned"))
  4043. (sql-redirect sqlbuf "\\a"))
  4044. ;; Return the list of table names (public schema name can be omitted)
  4045. (mapcar (lambda (tbl)
  4046. (if (string= (car tbl) "public")
  4047. (cadr tbl)
  4048. (format "%s.%s" (car tbl) (cadr tbl))))
  4049. cl)))
  4050. ;;;###autoload
  4051. (defun sql-interbase (&optional buffer)
  4052. "Run isql by Interbase as an inferior process.
  4053. If buffer `*SQL*' exists but no process is running, make a new process.
  4054. If buffer exists and a process is running, just switch to buffer
  4055. `*SQL*'.
  4056. Interpreter used comes from variable `sql-interbase-program'. Login
  4057. uses the variables `sql-user', `sql-password', and `sql-database' as
  4058. defaults, if set.
  4059. The buffer is put in SQL interactive mode, giving commands for sending
  4060. input. See `sql-interactive-mode'.
  4061. To set the buffer name directly, use \\[universal-argument]
  4062. before \\[sql-interbase]. Once session has started,
  4063. \\[sql-rename-buffer] can be called separately to rename the
  4064. buffer.
  4065. To specify a coding system for converting non-ASCII characters
  4066. in the input and output to the process, use \\[universal-coding-system-argument]
  4067. before \\[sql-interbase]. You can also specify this with \\[set-buffer-process-coding-system]
  4068. in the SQL buffer, after you start the process.
  4069. The default comes from `process-coding-system-alist' and
  4070. `default-process-coding-system'.
  4071. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  4072. (interactive "P")
  4073. (sql-product-interactive 'interbase buffer))
  4074. (defun sql-comint-interbase (product options)
  4075. "Create comint buffer and connect to Interbase."
  4076. ;; Put all parameters to the program (if defined) in a list and call
  4077. ;; make-comint.
  4078. (let ((params options))
  4079. (if (not (string= "" sql-user))
  4080. (setq params (append (list "-u" sql-user) params)))
  4081. (if (not (string= "" sql-password))
  4082. (setq params (append (list "-p" sql-password) params)))
  4083. (if (not (string= "" sql-database))
  4084. (setq params (cons sql-database params))) ; add to the front!
  4085. (sql-comint product params)))
  4086. ;;;###autoload
  4087. (defun sql-db2 (&optional buffer)
  4088. "Run db2 by IBM as an inferior process.
  4089. If buffer `*SQL*' exists but no process is running, make a new process.
  4090. If buffer exists and a process is running, just switch to buffer
  4091. `*SQL*'.
  4092. Interpreter used comes from variable `sql-db2-program'. There is not
  4093. automatic login.
  4094. The buffer is put in SQL interactive mode, giving commands for sending
  4095. input. See `sql-interactive-mode'.
  4096. If you use \\[sql-accumulate-and-indent] to send multiline commands to
  4097. db2, newlines will be escaped if necessary. If you don't want that, set
  4098. `comint-input-sender' back to `comint-simple-send' by writing an after
  4099. advice. See the elisp manual for more information.
  4100. To set the buffer name directly, use \\[universal-argument]
  4101. before \\[sql-db2]. Once session has started,
  4102. \\[sql-rename-buffer] can be called separately to rename the
  4103. buffer.
  4104. To specify a coding system for converting non-ASCII characters
  4105. in the input and output to the process, use \\[universal-coding-system-argument]
  4106. before \\[sql-db2]. You can also specify this with \\[set-buffer-process-coding-system]
  4107. in the SQL buffer, after you start the process.
  4108. The default comes from `process-coding-system-alist' and
  4109. `default-process-coding-system'.
  4110. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  4111. (interactive "P")
  4112. (sql-product-interactive 'db2 buffer))
  4113. (defun sql-comint-db2 (product options)
  4114. "Create comint buffer and connect to DB2."
  4115. ;; Put all parameters to the program (if defined) in a list and call
  4116. ;; make-comint.
  4117. (sql-comint product options))
  4118. ;;;###autoload
  4119. (defun sql-linter (&optional buffer)
  4120. "Run inl by RELEX as an inferior process.
  4121. If buffer `*SQL*' exists but no process is running, make a new process.
  4122. If buffer exists and a process is running, just switch to buffer
  4123. `*SQL*'.
  4124. Interpreter used comes from variable `sql-linter-program' - usually `inl'.
  4125. Login uses the variables `sql-user', `sql-password', `sql-database' and
  4126. `sql-server' as defaults, if set. Additional command line parameters
  4127. can be stored in the list `sql-linter-options'. Run inl -h to get help on
  4128. parameters.
  4129. `sql-database' is used to set the LINTER_MBX environment variable for
  4130. local connections, `sql-server' refers to the server name from the
  4131. `nodetab' file for the network connection (dbc_tcp or friends must run
  4132. for this to work). If `sql-password' is an empty string, inl will use
  4133. an empty password.
  4134. The buffer is put in SQL interactive mode, giving commands for sending
  4135. input. See `sql-interactive-mode'.
  4136. To set the buffer name directly, use \\[universal-argument]
  4137. before \\[sql-linter]. Once session has started,
  4138. \\[sql-rename-buffer] can be called separately to rename the
  4139. buffer.
  4140. \(Type \\[describe-mode] in the SQL buffer for a list of commands.)"
  4141. (interactive "P")
  4142. (sql-product-interactive 'linter buffer))
  4143. (defun sql-comint-linter (product options)
  4144. "Create comint buffer and connect to Linter."
  4145. ;; Put all parameters to the program (if defined) in a list and call
  4146. ;; make-comint.
  4147. (let ((params options)
  4148. (login nil)
  4149. (old-mbx (getenv "LINTER_MBX")))
  4150. (if (not (string= "" sql-user))
  4151. (setq login (concat sql-user "/" sql-password)))
  4152. (setq params (append (list "-u" login) params))
  4153. (if (not (string= "" sql-server))
  4154. (setq params (append (list "-n" sql-server) params)))
  4155. (if (string= "" sql-database)
  4156. (setenv "LINTER_MBX" nil)
  4157. (setenv "LINTER_MBX" sql-database))
  4158. (sql-comint product params)
  4159. (setenv "LINTER_MBX" old-mbx)))
  4160. (provide 'sql)
  4161. ;;; sql.el ends here
  4162. ; LocalWords: sql SQL SQLite sqlite Sybase Informix MySQL
  4163. ; LocalWords: Postgres SQLServer SQLi