elements.py 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383
  1. # sql/elements.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Core SQL expression elements, including :class:`_expression.ClauseElement`,
  8. :class:`_expression.ColumnElement`, and derived classes.
  9. """
  10. from __future__ import unicode_literals
  11. import itertools
  12. import operator
  13. import re
  14. from . import coercions
  15. from . import operators
  16. from . import roles
  17. from . import traversals
  18. from . import type_api
  19. from .annotation import Annotated
  20. from .annotation import SupportsWrappingAnnotations
  21. from .base import _clone
  22. from .base import _generative
  23. from .base import Executable
  24. from .base import HasMemoized
  25. from .base import Immutable
  26. from .base import NO_ARG
  27. from .base import PARSE_AUTOCOMMIT
  28. from .base import SingletonConstant
  29. from .coercions import _document_text_coercion
  30. from .traversals import HasCopyInternals
  31. from .traversals import MemoizedHasCacheKey
  32. from .traversals import NO_CACHE
  33. from .visitors import cloned_traverse
  34. from .visitors import InternalTraversal
  35. from .visitors import traverse
  36. from .visitors import Traversible
  37. from .. import exc
  38. from .. import inspection
  39. from .. import util
  40. def collate(expression, collation):
  41. """Return the clause ``expression COLLATE collation``.
  42. e.g.::
  43. collate(mycolumn, 'utf8_bin')
  44. produces::
  45. mycolumn COLLATE utf8_bin
  46. The collation expression is also quoted if it is a case sensitive
  47. identifier, e.g. contains uppercase characters.
  48. .. versionchanged:: 1.2 quoting is automatically applied to COLLATE
  49. expressions if they are case sensitive.
  50. """
  51. expr = coercions.expect(roles.ExpressionElementRole, expression)
  52. return BinaryExpression(
  53. expr, CollationClause(collation), operators.collate, type_=expr.type
  54. )
  55. def between(expr, lower_bound, upper_bound, symmetric=False):
  56. """Produce a ``BETWEEN`` predicate clause.
  57. E.g.::
  58. from sqlalchemy import between
  59. stmt = select(users_table).where(between(users_table.c.id, 5, 7))
  60. Would produce SQL resembling::
  61. SELECT id, name FROM user WHERE id BETWEEN :id_1 AND :id_2
  62. The :func:`.between` function is a standalone version of the
  63. :meth:`_expression.ColumnElement.between` method available on all
  64. SQL expressions, as in::
  65. stmt = select(users_table).where(users_table.c.id.between(5, 7))
  66. All arguments passed to :func:`.between`, including the left side
  67. column expression, are coerced from Python scalar values if a
  68. the value is not a :class:`_expression.ColumnElement` subclass.
  69. For example,
  70. three fixed values can be compared as in::
  71. print(between(5, 3, 7))
  72. Which would produce::
  73. :param_1 BETWEEN :param_2 AND :param_3
  74. :param expr: a column expression, typically a
  75. :class:`_expression.ColumnElement`
  76. instance or alternatively a Python scalar expression to be coerced
  77. into a column expression, serving as the left side of the ``BETWEEN``
  78. expression.
  79. :param lower_bound: a column or Python scalar expression serving as the
  80. lower bound of the right side of the ``BETWEEN`` expression.
  81. :param upper_bound: a column or Python scalar expression serving as the
  82. upper bound of the right side of the ``BETWEEN`` expression.
  83. :param symmetric: if True, will render " BETWEEN SYMMETRIC ". Note
  84. that not all databases support this syntax.
  85. .. versionadded:: 0.9.5
  86. .. seealso::
  87. :meth:`_expression.ColumnElement.between`
  88. """
  89. expr = coercions.expect(roles.ExpressionElementRole, expr)
  90. return expr.between(lower_bound, upper_bound, symmetric=symmetric)
  91. def literal(value, type_=None):
  92. r"""Return a literal clause, bound to a bind parameter.
  93. Literal clauses are created automatically when non-
  94. :class:`_expression.ClauseElement` objects (such as strings, ints, dates,
  95. etc.) are
  96. used in a comparison operation with a :class:`_expression.ColumnElement`
  97. subclass,
  98. such as a :class:`~sqlalchemy.schema.Column` object. Use this function
  99. to force the generation of a literal clause, which will be created as a
  100. :class:`BindParameter` with a bound value.
  101. :param value: the value to be bound. Can be any Python object supported by
  102. the underlying DB-API, or is translatable via the given type argument.
  103. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which
  104. will provide bind-parameter translation for this literal.
  105. """
  106. return coercions.expect(roles.LiteralValueRole, value, type_=type_)
  107. def outparam(key, type_=None):
  108. """Create an 'OUT' parameter for usage in functions (stored procedures),
  109. for databases which support them.
  110. The ``outparam`` can be used like a regular function parameter.
  111. The "output" value will be available from the
  112. :class:`~sqlalchemy.engine.CursorResult` object via its ``out_parameters``
  113. attribute, which returns a dictionary containing the values.
  114. """
  115. return BindParameter(key, None, type_=type_, unique=False, isoutparam=True)
  116. def not_(clause):
  117. """Return a negation of the given clause, i.e. ``NOT(clause)``.
  118. The ``~`` operator is also overloaded on all
  119. :class:`_expression.ColumnElement` subclasses to produce the
  120. same result.
  121. """
  122. return operators.inv(coercions.expect(roles.ExpressionElementRole, clause))
  123. @inspection._self_inspects
  124. class ClauseElement(
  125. roles.SQLRole,
  126. SupportsWrappingAnnotations,
  127. MemoizedHasCacheKey,
  128. HasCopyInternals,
  129. Traversible,
  130. ):
  131. """Base class for elements of a programmatically constructed SQL
  132. expression.
  133. """
  134. __visit_name__ = "clause"
  135. _propagate_attrs = util.immutabledict()
  136. """like annotations, however these propagate outwards liberally
  137. as SQL constructs are built, and are set up at construction time.
  138. """
  139. supports_execution = False
  140. stringify_dialect = "default"
  141. _from_objects = []
  142. bind = None
  143. description = None
  144. _is_clone_of = None
  145. is_clause_element = True
  146. is_selectable = False
  147. _is_textual = False
  148. _is_from_clause = False
  149. _is_returns_rows = False
  150. _is_text_clause = False
  151. _is_from_container = False
  152. _is_select_container = False
  153. _is_select_statement = False
  154. _is_bind_parameter = False
  155. _is_clause_list = False
  156. _is_lambda_element = False
  157. _is_singleton_constant = False
  158. _is_immutable = False
  159. _order_by_label_element = None
  160. _cache_key_traversal = None
  161. def _set_propagate_attrs(self, values):
  162. # usually, self._propagate_attrs is empty here. one case where it's
  163. # not is a subquery against ORM select, that is then pulled as a
  164. # property of an aliased class. should all be good
  165. # assert not self._propagate_attrs
  166. self._propagate_attrs = util.immutabledict(values)
  167. return self
  168. def _clone(self, **kw):
  169. """Create a shallow copy of this ClauseElement.
  170. This method may be used by a generative API. Its also used as
  171. part of the "deep" copy afforded by a traversal that combines
  172. the _copy_internals() method.
  173. """
  174. skip = self._memoized_keys
  175. c = self.__class__.__new__(self.__class__)
  176. c.__dict__ = {k: v for k, v in self.__dict__.items() if k not in skip}
  177. # this is a marker that helps to "equate" clauses to each other
  178. # when a Select returns its list of FROM clauses. the cloning
  179. # process leaves around a lot of remnants of the previous clause
  180. # typically in the form of column expressions still attached to the
  181. # old table.
  182. c._is_clone_of = self
  183. return c
  184. def _negate_in_binary(self, negated_op, original_op):
  185. """a hook to allow the right side of a binary expression to respond
  186. to a negation of the binary expression.
  187. Used for the special case of expanding bind parameter with IN.
  188. """
  189. return self
  190. def _with_binary_element_type(self, type_):
  191. """in the context of binary expression, convert the type of this
  192. object to the one given.
  193. applies only to :class:`_expression.ColumnElement` classes.
  194. """
  195. return self
  196. @property
  197. def _constructor(self):
  198. """return the 'constructor' for this ClauseElement.
  199. This is for the purposes for creating a new object of
  200. this type. Usually, its just the element's __class__.
  201. However, the "Annotated" version of the object overrides
  202. to return the class of its proxied element.
  203. """
  204. return self.__class__
  205. @HasMemoized.memoized_attribute
  206. def _cloned_set(self):
  207. """Return the set consisting all cloned ancestors of this
  208. ClauseElement.
  209. Includes this ClauseElement. This accessor tends to be used for
  210. FromClause objects to identify 'equivalent' FROM clauses, regardless
  211. of transformative operations.
  212. """
  213. s = util.column_set()
  214. f = self
  215. # note this creates a cycle, asserted in test_memusage. however,
  216. # turning this into a plain @property adds tends of thousands of method
  217. # calls to Core / ORM performance tests, so the small overhead
  218. # introduced by the relatively small amount of short term cycles
  219. # produced here is preferable
  220. while f is not None:
  221. s.add(f)
  222. f = f._is_clone_of
  223. return s
  224. @property
  225. def entity_namespace(self):
  226. raise AttributeError(
  227. "This SQL expression has no entity namespace "
  228. "with which to filter from."
  229. )
  230. def __getstate__(self):
  231. d = self.__dict__.copy()
  232. d.pop("_is_clone_of", None)
  233. d.pop("_generate_cache_key", None)
  234. return d
  235. def _execute_on_connection(
  236. self, connection, multiparams, params, execution_options, _force=False
  237. ):
  238. if _force or self.supports_execution:
  239. return connection._execute_clauseelement(
  240. self, multiparams, params, execution_options
  241. )
  242. else:
  243. raise exc.ObjectNotExecutableError(self)
  244. def unique_params(self, *optionaldict, **kwargs):
  245. """Return a copy with :func:`_expression.bindparam` elements
  246. replaced.
  247. Same functionality as :meth:`_expression.ClauseElement.params`,
  248. except adds `unique=True`
  249. to affected bind parameters so that multiple statements can be
  250. used.
  251. """
  252. return self._replace_params(True, optionaldict, kwargs)
  253. def params(self, *optionaldict, **kwargs):
  254. """Return a copy with :func:`_expression.bindparam` elements
  255. replaced.
  256. Returns a copy of this ClauseElement with
  257. :func:`_expression.bindparam`
  258. elements replaced with values taken from the given dictionary::
  259. >>> clause = column('x') + bindparam('foo')
  260. >>> print(clause.compile().params)
  261. {'foo':None}
  262. >>> print(clause.params({'foo':7}).compile().params)
  263. {'foo':7}
  264. """
  265. return self._replace_params(False, optionaldict, kwargs)
  266. def _replace_params(self, unique, optionaldict, kwargs):
  267. if len(optionaldict) == 1:
  268. kwargs.update(optionaldict[0])
  269. elif len(optionaldict) > 1:
  270. raise exc.ArgumentError(
  271. "params() takes zero or one positional dictionary argument"
  272. )
  273. def visit_bindparam(bind):
  274. if bind.key in kwargs:
  275. bind.value = kwargs[bind.key]
  276. bind.required = False
  277. if unique:
  278. bind._convert_to_unique()
  279. return cloned_traverse(
  280. self,
  281. {"maintain_key": True, "detect_subquery_cols": True},
  282. {"bindparam": visit_bindparam},
  283. )
  284. def compare(self, other, **kw):
  285. r"""Compare this :class:`_expression.ClauseElement` to
  286. the given :class:`_expression.ClauseElement`.
  287. Subclasses should override the default behavior, which is a
  288. straight identity comparison.
  289. \**kw are arguments consumed by subclass ``compare()`` methods and
  290. may be used to modify the criteria for comparison
  291. (see :class:`_expression.ColumnElement`).
  292. """
  293. return traversals.compare(self, other, **kw)
  294. def self_group(self, against=None):
  295. """Apply a 'grouping' to this :class:`_expression.ClauseElement`.
  296. This method is overridden by subclasses to return a "grouping"
  297. construct, i.e. parenthesis. In particular it's used by "binary"
  298. expressions to provide a grouping around themselves when placed into a
  299. larger expression, as well as by :func:`_expression.select`
  300. constructs when placed into the FROM clause of another
  301. :func:`_expression.select`. (Note that subqueries should be
  302. normally created using the :meth:`_expression.Select.alias` method,
  303. as many
  304. platforms require nested SELECT statements to be named).
  305. As expressions are composed together, the application of
  306. :meth:`self_group` is automatic - end-user code should never
  307. need to use this method directly. Note that SQLAlchemy's
  308. clause constructs take operator precedence into account -
  309. so parenthesis might not be needed, for example, in
  310. an expression like ``x OR (y AND z)`` - AND takes precedence
  311. over OR.
  312. The base :meth:`self_group` method of
  313. :class:`_expression.ClauseElement`
  314. just returns self.
  315. """
  316. return self
  317. def _ungroup(self):
  318. """Return this :class:`_expression.ClauseElement`
  319. without any groupings.
  320. """
  321. return self
  322. @util.preload_module("sqlalchemy.engine.default")
  323. @util.preload_module("sqlalchemy.engine.url")
  324. def compile(self, bind=None, dialect=None, **kw):
  325. """Compile this SQL expression.
  326. The return value is a :class:`~.Compiled` object.
  327. Calling ``str()`` or ``unicode()`` on the returned value will yield a
  328. string representation of the result. The
  329. :class:`~.Compiled` object also can return a
  330. dictionary of bind parameter names and values
  331. using the ``params`` accessor.
  332. :param bind: An ``Engine`` or ``Connection`` from which a
  333. ``Compiled`` will be acquired. This argument takes precedence over
  334. this :class:`_expression.ClauseElement`'s bound engine, if any.
  335. :param column_keys: Used for INSERT and UPDATE statements, a list of
  336. column names which should be present in the VALUES clause of the
  337. compiled statement. If ``None``, all columns from the target table
  338. object are rendered.
  339. :param dialect: A ``Dialect`` instance from which a ``Compiled``
  340. will be acquired. This argument takes precedence over the `bind`
  341. argument as well as this :class:`_expression.ClauseElement`
  342. 's bound engine,
  343. if any.
  344. :param compile_kwargs: optional dictionary of additional parameters
  345. that will be passed through to the compiler within all "visit"
  346. methods. This allows any custom flag to be passed through to
  347. a custom compilation construct, for example. It is also used
  348. for the case of passing the ``literal_binds`` flag through::
  349. from sqlalchemy.sql import table, column, select
  350. t = table('t', column('x'))
  351. s = select(t).where(t.c.x == 5)
  352. print(s.compile(compile_kwargs={"literal_binds": True}))
  353. .. versionadded:: 0.9.0
  354. .. seealso::
  355. :ref:`faq_sql_expression_string`
  356. """
  357. if not dialect:
  358. if bind:
  359. dialect = bind.dialect
  360. elif self.bind:
  361. dialect = self.bind.dialect
  362. else:
  363. if self.stringify_dialect == "default":
  364. default = util.preloaded.engine_default
  365. dialect = default.StrCompileDialect()
  366. else:
  367. url = util.preloaded.engine_url
  368. dialect = url.URL.create(
  369. self.stringify_dialect
  370. ).get_dialect()()
  371. return self._compiler(dialect, **kw)
  372. def _compile_w_cache(
  373. self,
  374. dialect,
  375. compiled_cache=None,
  376. column_keys=None,
  377. for_executemany=False,
  378. schema_translate_map=None,
  379. **kw
  380. ):
  381. if compiled_cache is not None and dialect._supports_statement_cache:
  382. elem_cache_key = self._generate_cache_key()
  383. else:
  384. elem_cache_key = None
  385. if elem_cache_key:
  386. cache_key, extracted_params = elem_cache_key
  387. key = (
  388. dialect,
  389. cache_key,
  390. tuple(column_keys),
  391. bool(schema_translate_map),
  392. for_executemany,
  393. )
  394. compiled_sql = compiled_cache.get(key)
  395. if compiled_sql is None:
  396. cache_hit = dialect.CACHE_MISS
  397. compiled_sql = self._compiler(
  398. dialect,
  399. cache_key=elem_cache_key,
  400. column_keys=column_keys,
  401. for_executemany=for_executemany,
  402. schema_translate_map=schema_translate_map,
  403. **kw
  404. )
  405. compiled_cache[key] = compiled_sql
  406. else:
  407. cache_hit = dialect.CACHE_HIT
  408. else:
  409. extracted_params = None
  410. compiled_sql = self._compiler(
  411. dialect,
  412. cache_key=elem_cache_key,
  413. column_keys=column_keys,
  414. for_executemany=for_executemany,
  415. schema_translate_map=schema_translate_map,
  416. **kw
  417. )
  418. if not dialect._supports_statement_cache:
  419. cache_hit = dialect.NO_DIALECT_SUPPORT
  420. elif compiled_cache is None:
  421. cache_hit = dialect.CACHING_DISABLED
  422. else:
  423. cache_hit = dialect.NO_CACHE_KEY
  424. return compiled_sql, extracted_params, cache_hit
  425. def _compiler(self, dialect, **kw):
  426. """Return a compiler appropriate for this ClauseElement, given a
  427. Dialect."""
  428. return dialect.statement_compiler(dialect, self, **kw)
  429. def __str__(self):
  430. if util.py3k:
  431. return str(self.compile())
  432. else:
  433. return unicode(self.compile()).encode( # noqa
  434. "ascii", "backslashreplace"
  435. ) # noqa
  436. def __invert__(self):
  437. # undocumented element currently used by the ORM for
  438. # relationship.contains()
  439. if hasattr(self, "negation_clause"):
  440. return self.negation_clause
  441. else:
  442. return self._negate()
  443. def _negate(self):
  444. return UnaryExpression(
  445. self.self_group(against=operators.inv), operator=operators.inv
  446. )
  447. def __bool__(self):
  448. raise TypeError("Boolean value of this clause is not defined")
  449. __nonzero__ = __bool__
  450. def __repr__(self):
  451. friendly = self.description
  452. if friendly is None:
  453. return object.__repr__(self)
  454. else:
  455. return "<%s.%s at 0x%x; %s>" % (
  456. self.__module__,
  457. self.__class__.__name__,
  458. id(self),
  459. friendly,
  460. )
  461. class ColumnElement(
  462. roles.ColumnArgumentOrKeyRole,
  463. roles.StatementOptionRole,
  464. roles.WhereHavingRole,
  465. roles.BinaryElementRole,
  466. roles.OrderByRole,
  467. roles.ColumnsClauseRole,
  468. roles.LimitOffsetRole,
  469. roles.DMLColumnRole,
  470. roles.DDLConstraintColumnRole,
  471. roles.DDLExpressionRole,
  472. operators.ColumnOperators,
  473. ClauseElement,
  474. ):
  475. """Represent a column-oriented SQL expression suitable for usage in the
  476. "columns" clause, WHERE clause etc. of a statement.
  477. While the most familiar kind of :class:`_expression.ColumnElement` is the
  478. :class:`_schema.Column` object, :class:`_expression.ColumnElement`
  479. serves as the basis
  480. for any unit that may be present in a SQL expression, including
  481. the expressions themselves, SQL functions, bound parameters,
  482. literal expressions, keywords such as ``NULL``, etc.
  483. :class:`_expression.ColumnElement`
  484. is the ultimate base class for all such elements.
  485. A wide variety of SQLAlchemy Core functions work at the SQL expression
  486. level, and are intended to accept instances of
  487. :class:`_expression.ColumnElement` as
  488. arguments. These functions will typically document that they accept a
  489. "SQL expression" as an argument. What this means in terms of SQLAlchemy
  490. usually refers to an input which is either already in the form of a
  491. :class:`_expression.ColumnElement` object,
  492. or a value which can be **coerced** into
  493. one. The coercion rules followed by most, but not all, SQLAlchemy Core
  494. functions with regards to SQL expressions are as follows:
  495. * a literal Python value, such as a string, integer or floating
  496. point value, boolean, datetime, ``Decimal`` object, or virtually
  497. any other Python object, will be coerced into a "literal bound
  498. value". This generally means that a :func:`.bindparam` will be
  499. produced featuring the given value embedded into the construct; the
  500. resulting :class:`.BindParameter` object is an instance of
  501. :class:`_expression.ColumnElement`.
  502. The Python value will ultimately be sent
  503. to the DBAPI at execution time as a parameterized argument to the
  504. ``execute()`` or ``executemany()`` methods, after SQLAlchemy
  505. type-specific converters (e.g. those provided by any associated
  506. :class:`.TypeEngine` objects) are applied to the value.
  507. * any special object value, typically ORM-level constructs, which
  508. feature an accessor called ``__clause_element__()``. The Core
  509. expression system looks for this method when an object of otherwise
  510. unknown type is passed to a function that is looking to coerce the
  511. argument into a :class:`_expression.ColumnElement` and sometimes a
  512. :class:`_expression.SelectBase` expression.
  513. It is used within the ORM to
  514. convert from ORM-specific objects like mapped classes and
  515. mapped attributes into Core expression objects.
  516. * The Python ``None`` value is typically interpreted as ``NULL``,
  517. which in SQLAlchemy Core produces an instance of :func:`.null`.
  518. A :class:`_expression.ColumnElement` provides the ability to generate new
  519. :class:`_expression.ColumnElement`
  520. objects using Python expressions. This means that Python operators
  521. such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations,
  522. and allow the instantiation of further :class:`_expression.ColumnElement`
  523. instances
  524. which are composed from other, more fundamental
  525. :class:`_expression.ColumnElement`
  526. objects. For example, two :class:`.ColumnClause` objects can be added
  527. together with the addition operator ``+`` to produce
  528. a :class:`.BinaryExpression`.
  529. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses
  530. of :class:`_expression.ColumnElement`::
  531. >>> from sqlalchemy.sql import column
  532. >>> column('a') + column('b')
  533. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  534. >>> print(column('a') + column('b'))
  535. a + b
  536. .. seealso::
  537. :class:`_schema.Column`
  538. :func:`_expression.column`
  539. """
  540. __visit_name__ = "column_element"
  541. primary_key = False
  542. foreign_keys = []
  543. _proxies = ()
  544. _tq_label = None
  545. """The named label that can be used to target
  546. this column in a result set in a "table qualified" context.
  547. This label is almost always the label used when
  548. rendering <expr> AS <label> in a SELECT statement when using
  549. the LABEL_STYLE_TABLENAME_PLUS_COL label style, which is what the legacy
  550. ORM ``Query`` object uses as well.
  551. For a regular Column bound to a Table, this is typically the label
  552. <tablename>_<columnname>. For other constructs, different rules
  553. may apply, such as anonymized labels and others.
  554. .. versionchanged:: 1.4.21 renamed from ``._label``
  555. """
  556. key = None
  557. """The 'key' that in some circumstances refers to this object in a
  558. Python namespace.
  559. This typically refers to the "key" of the column as present in the
  560. ``.c`` collection of a selectable, e.g. ``sometable.c["somekey"]`` would
  561. return a :class:`_schema.Column` with a ``.key`` of "somekey".
  562. """
  563. @HasMemoized.memoized_attribute
  564. def _tq_key_label(self):
  565. """A label-based version of 'key' that in some circumstances refers
  566. to this object in a Python namespace.
  567. _tq_key_label comes into play when a select() statement is constructed
  568. with apply_labels(); in this case, all Column objects in the ``.c``
  569. collection are rendered as <tablename>_<columnname> in SQL; this is
  570. essentially the value of ._label. But to locate those columns in the
  571. ``.c`` collection, the name is along the lines of <tablename>_<key>;
  572. that's the typical value of .key_label.
  573. .. versionchanged:: 1.4.21 renamed from ``._key_label``
  574. """
  575. return self._proxy_key
  576. @property
  577. def _key_label(self):
  578. """legacy; renamed to _tq_key_label"""
  579. return self._tq_key_label
  580. @property
  581. def _label(self):
  582. """legacy; renamed to _tq_label"""
  583. return self._tq_label
  584. @property
  585. def _non_anon_label(self):
  586. """the 'name' that naturally applies this element when rendered in
  587. SQL.
  588. Concretely, this is the "name" of a column or a label in a
  589. SELECT statement; ``<columnname>`` and ``<labelname>`` below::
  590. SELECT <columnmame> FROM table
  591. SELECT column AS <labelname> FROM table
  592. Above, the two names noted will be what's present in the DBAPI
  593. ``cursor.description`` as the names.
  594. If this attribute returns ``None``, it means that the SQL element as
  595. written does not have a 100% fully predictable "name" that would appear
  596. in the ``cursor.description``. Examples include SQL functions, CAST
  597. functions, etc. While such things do return names in
  598. ``cursor.description``, they are only predictable on a
  599. database-specific basis; e.g. an expression like ``MAX(table.col)`` may
  600. appear as the string ``max`` on one database (like PostgreSQL) or may
  601. appear as the whole expression ``max(table.col)`` on SQLite.
  602. The default implementation looks for a ``.name`` attribute on the
  603. object, as has been the precedent established in SQLAlchemy for many
  604. years. An exception is made on the ``FunctionElement`` subclass
  605. so that the return value is always ``None``.
  606. .. versionadded:: 1.4.21
  607. """
  608. return getattr(self, "name", None)
  609. _render_label_in_columns_clause = True
  610. """A flag used by select._columns_plus_names that helps to determine
  611. we are actually going to render in terms of "SELECT <col> AS <label>".
  612. This flag can be returned as False for some Column objects that want
  613. to be rendered as simple "SELECT <col>"; typically columns that don't have
  614. any parent table and are named the same as what the label would be
  615. in any case.
  616. """
  617. _allow_label_resolve = True
  618. """A flag that can be flipped to prevent a column from being resolvable
  619. by string label name.
  620. The joined eager loader strategy in the ORM uses this, for example.
  621. """
  622. _is_implicitly_boolean = False
  623. _alt_names = ()
  624. def self_group(self, against=None):
  625. if (
  626. against in (operators.and_, operators.or_, operators._asbool)
  627. and self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity
  628. ):
  629. return AsBoolean(self, operators.is_true, operators.is_false)
  630. elif against in (operators.any_op, operators.all_op):
  631. return Grouping(self)
  632. else:
  633. return self
  634. def _negate(self):
  635. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  636. return AsBoolean(self, operators.is_false, operators.is_true)
  637. else:
  638. return super(ColumnElement, self)._negate()
  639. @util.memoized_property
  640. def type(self):
  641. return type_api.NULLTYPE
  642. @HasMemoized.memoized_attribute
  643. def comparator(self):
  644. try:
  645. comparator_factory = self.type.comparator_factory
  646. except AttributeError as err:
  647. util.raise_(
  648. TypeError(
  649. "Object %r associated with '.type' attribute "
  650. "is not a TypeEngine class or object" % self.type
  651. ),
  652. replace_context=err,
  653. )
  654. else:
  655. return comparator_factory(self)
  656. def __getattr__(self, key):
  657. try:
  658. return getattr(self.comparator, key)
  659. except AttributeError as err:
  660. util.raise_(
  661. AttributeError(
  662. "Neither %r object nor %r object has an attribute %r"
  663. % (
  664. type(self).__name__,
  665. type(self.comparator).__name__,
  666. key,
  667. )
  668. ),
  669. replace_context=err,
  670. )
  671. def operate(self, op, *other, **kwargs):
  672. return op(self.comparator, *other, **kwargs)
  673. def reverse_operate(self, op, other, **kwargs):
  674. return op(other, self.comparator, **kwargs)
  675. def _bind_param(self, operator, obj, type_=None, expanding=False):
  676. return BindParameter(
  677. None,
  678. obj,
  679. _compared_to_operator=operator,
  680. type_=type_,
  681. _compared_to_type=self.type,
  682. unique=True,
  683. expanding=expanding,
  684. )
  685. @property
  686. def expression(self):
  687. """Return a column expression.
  688. Part of the inspection interface; returns self.
  689. """
  690. return self
  691. @property
  692. def _select_iterable(self):
  693. return (self,)
  694. @util.memoized_property
  695. def base_columns(self):
  696. return util.column_set(c for c in self.proxy_set if not c._proxies)
  697. @util.memoized_property
  698. def proxy_set(self):
  699. s = util.column_set([self])
  700. for c in self._proxies:
  701. s.update(c.proxy_set)
  702. return s
  703. def _uncached_proxy_set(self):
  704. """An 'uncached' version of proxy set.
  705. This is so that we can read annotations from the list of columns
  706. without breaking the caching of the above proxy_set.
  707. """
  708. s = util.column_set([self])
  709. for c in self._proxies:
  710. s.update(c._uncached_proxy_set())
  711. return s
  712. def shares_lineage(self, othercolumn):
  713. """Return True if the given :class:`_expression.ColumnElement`
  714. has a common ancestor to this :class:`_expression.ColumnElement`."""
  715. return bool(self.proxy_set.intersection(othercolumn.proxy_set))
  716. def _compare_name_for_result(self, other):
  717. """Return True if the given column element compares to this one
  718. when targeting within a result row."""
  719. return (
  720. hasattr(other, "name")
  721. and hasattr(self, "name")
  722. and other.name == self.name
  723. )
  724. @HasMemoized.memoized_attribute
  725. def _proxy_key(self):
  726. if self._annotations and "proxy_key" in self._annotations:
  727. return self._annotations["proxy_key"]
  728. name = self.key
  729. if not name:
  730. # there's a bit of a seeming contradiction which is that the
  731. # "_non_anon_label" of a column can in fact be an
  732. # "_anonymous_label"; this is when it's on a column that is
  733. # proxying for an anonymous expression in a subquery.
  734. name = self._non_anon_label
  735. if isinstance(name, _anonymous_label):
  736. return None
  737. else:
  738. return name
  739. @HasMemoized.memoized_attribute
  740. def _expression_label(self):
  741. """a suggested label to use in the case that the column has no name,
  742. which should be used if possible as the explicit 'AS <label>'
  743. where this expression would normally have an anon label.
  744. this is essentially mostly what _proxy_key does except it returns
  745. None if the column has a normal name that can be used.
  746. """
  747. if getattr(self, "name", None) is not None:
  748. return None
  749. elif self._annotations and "proxy_key" in self._annotations:
  750. return self._annotations["proxy_key"]
  751. else:
  752. return None
  753. def _make_proxy(
  754. self, selectable, name=None, key=None, name_is_truncatable=False, **kw
  755. ):
  756. """Create a new :class:`_expression.ColumnElement` representing this
  757. :class:`_expression.ColumnElement` as it appears in the select list of
  758. a descending selectable.
  759. """
  760. if name is None:
  761. name = self._anon_name_label
  762. if key is None:
  763. key = self._proxy_key
  764. else:
  765. key = name
  766. co = ColumnClause(
  767. coercions.expect(roles.TruncatedLabelRole, name)
  768. if name_is_truncatable
  769. else name,
  770. type_=getattr(self, "type", None),
  771. _selectable=selectable,
  772. )
  773. co._propagate_attrs = selectable._propagate_attrs
  774. co._proxies = [self]
  775. if selectable._is_clone_of is not None:
  776. co._is_clone_of = selectable._is_clone_of.columns.get(key)
  777. return key, co
  778. def cast(self, type_):
  779. """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``.
  780. This is a shortcut to the :func:`_expression.cast` function.
  781. .. seealso::
  782. :ref:`coretutorial_casts`
  783. :func:`_expression.cast`
  784. :func:`_expression.type_coerce`
  785. .. versionadded:: 1.0.7
  786. """
  787. return Cast(self, type_)
  788. def label(self, name):
  789. """Produce a column label, i.e. ``<columnname> AS <name>``.
  790. This is a shortcut to the :func:`_expression.label` function.
  791. If 'name' is ``None``, an anonymous label name will be generated.
  792. """
  793. return Label(name, self, self.type)
  794. def _anon_label(self, seed, add_hash=None):
  795. while self._is_clone_of is not None:
  796. self = self._is_clone_of
  797. # as of 1.4 anonymous label for ColumnElement uses hash(), not id(),
  798. # as the identifier, because a column and its annotated version are
  799. # the same thing in a SQL statement
  800. hash_value = hash(self)
  801. if add_hash:
  802. # this path is used for disambiguating anon labels that would
  803. # otherwise be the same name for the same element repeated.
  804. # an additional numeric value is factored in for each label.
  805. # shift hash(self) (which is id(self), typically 8 byte integer)
  806. # 16 bits leftward. fill extra add_hash on right
  807. assert add_hash < (2 << 15)
  808. assert seed
  809. hash_value = (hash_value << 16) | add_hash
  810. # extra underscore is added for labels with extra hash
  811. # values, to isolate the "deduped anon" namespace from the
  812. # regular namespace. eliminates chance of these
  813. # manufactured hash values overlapping with regular ones for some
  814. # undefined python interpreter
  815. seed = seed + "_"
  816. if isinstance(seed, _anonymous_label):
  817. return _anonymous_label.safe_construct(
  818. hash_value, "", enclosing_label=seed
  819. )
  820. return _anonymous_label.safe_construct(hash_value, seed or "anon")
  821. @util.memoized_property
  822. def _anon_name_label(self):
  823. """Provides a constant 'anonymous label' for this ColumnElement.
  824. This is a label() expression which will be named at compile time.
  825. The same label() is returned each time ``anon_label`` is called so
  826. that expressions can reference ``anon_label`` multiple times,
  827. producing the same label name at compile time.
  828. The compiler uses this function automatically at compile time
  829. for expressions that are known to be 'unnamed' like binary
  830. expressions and function calls.
  831. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  832. public and is renamed to _anon_name_label. anon_name exists
  833. for backwards compat
  834. """
  835. name = getattr(self, "name", None)
  836. return self._anon_label(name)
  837. @util.memoized_property
  838. def _anon_key_label(self):
  839. """Provides a constant 'anonymous key label' for this ColumnElement.
  840. Compare to ``anon_label``, except that the "key" of the column,
  841. if available, is used to generate the label.
  842. This is used when a deduplicating key is placed into the columns
  843. collection of a selectable.
  844. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  845. public and is renamed to _anon_key_label. anon_key_label exists
  846. for backwards compat
  847. """
  848. return self._anon_label(self._proxy_key)
  849. @property
  850. @util.deprecated(
  851. "1.4",
  852. "The :attr:`_expression.ColumnElement.anon_label` attribute is now "
  853. "private, and the public accessor is deprecated.",
  854. )
  855. def anon_label(self):
  856. return self._anon_name_label
  857. @property
  858. @util.deprecated(
  859. "1.4",
  860. "The :attr:`_expression.ColumnElement.anon_key_label` attribute is "
  861. "now private, and the public accessor is deprecated.",
  862. )
  863. def anon_key_label(self):
  864. return self._anon_key_label
  865. def _dedupe_anon_label_idx(self, idx):
  866. """label to apply to a column that is anon labeled, but repeated
  867. in the SELECT, so that we have to make an "extra anon" label that
  868. disambiguates it from the previous appearance.
  869. these labels come out like "foo_bar_id__1" and have double underscores
  870. in them.
  871. """
  872. label = getattr(self, "name", None)
  873. # current convention is that if the element doesn't have a
  874. # ".name" (usually because it is not NamedColumn), we try to
  875. # use a "table qualified" form for the "dedupe anon" label,
  876. # based on the notion that a label like
  877. # "CAST(casttest.v1 AS DECIMAL) AS casttest_v1__1" looks better than
  878. # "CAST(casttest.v1 AS DECIMAL) AS anon__1"
  879. if label is None:
  880. return self._dedupe_anon_tq_label_idx(idx)
  881. else:
  882. return self._anon_label(label, add_hash=idx)
  883. @util.memoized_property
  884. def _anon_tq_label(self):
  885. return self._anon_label(getattr(self, "_tq_label", None))
  886. @util.memoized_property
  887. def _anon_tq_key_label(self):
  888. return self._anon_label(getattr(self, "_tq_key_label", None))
  889. def _dedupe_anon_tq_label_idx(self, idx):
  890. label = getattr(self, "_tq_label", None) or "anon"
  891. return self._anon_label(label, add_hash=idx)
  892. class WrapsColumnExpression(object):
  893. """Mixin that defines a :class:`_expression.ColumnElement`
  894. as a wrapper with special
  895. labeling behavior for an expression that already has a name.
  896. .. versionadded:: 1.4
  897. .. seealso::
  898. :ref:`change_4449`
  899. """
  900. @property
  901. def wrapped_column_expression(self):
  902. raise NotImplementedError()
  903. @property
  904. def _tq_label(self):
  905. wce = self.wrapped_column_expression
  906. if hasattr(wce, "_tq_label"):
  907. return wce._tq_label
  908. else:
  909. return None
  910. _label = _tq_label
  911. @property
  912. def _non_anon_label(self):
  913. return None
  914. @property
  915. def _anon_name_label(self):
  916. wce = self.wrapped_column_expression
  917. # this logic tries to get the WrappedColumnExpression to render
  918. # with "<expr> AS <name>", where "<name>" is the natural name
  919. # within the expression itself. e.g. "CAST(table.foo) AS foo".
  920. if not wce._is_text_clause:
  921. nal = wce._non_anon_label
  922. if nal:
  923. return nal
  924. elif hasattr(wce, "_anon_name_label"):
  925. return wce._anon_name_label
  926. return super(WrapsColumnExpression, self)._anon_name_label
  927. def _dedupe_anon_label_idx(self, idx):
  928. wce = self.wrapped_column_expression
  929. nal = wce._non_anon_label
  930. if nal:
  931. return self._anon_label(nal + "_")
  932. else:
  933. return self._dedupe_anon_tq_label_idx(idx)
  934. class BindParameter(roles.InElementRole, ColumnElement):
  935. r"""Represent a "bound expression".
  936. :class:`.BindParameter` is invoked explicitly using the
  937. :func:`.bindparam` function, as in::
  938. from sqlalchemy import bindparam
  939. stmt = select(users_table).\
  940. where(users_table.c.name == bindparam('username'))
  941. Detailed discussion of how :class:`.BindParameter` is used is
  942. at :func:`.bindparam`.
  943. .. seealso::
  944. :func:`.bindparam`
  945. """
  946. __visit_name__ = "bindparam"
  947. _traverse_internals = [
  948. ("key", InternalTraversal.dp_anon_name),
  949. ("type", InternalTraversal.dp_type),
  950. ("callable", InternalTraversal.dp_plain_dict),
  951. ("value", InternalTraversal.dp_plain_obj),
  952. ]
  953. _is_crud = False
  954. _is_bind_parameter = True
  955. _key_is_anon = False
  956. # bindparam implements its own _gen_cache_key() method however
  957. # we check subclasses for this flag, else no cache key is generated
  958. inherit_cache = True
  959. def __init__(
  960. self,
  961. key,
  962. value=NO_ARG,
  963. type_=None,
  964. unique=False,
  965. required=NO_ARG,
  966. quote=None,
  967. callable_=None,
  968. expanding=False,
  969. isoutparam=False,
  970. literal_execute=False,
  971. _compared_to_operator=None,
  972. _compared_to_type=None,
  973. _is_crud=False,
  974. ):
  975. r"""Produce a "bound expression".
  976. The return value is an instance of :class:`.BindParameter`; this
  977. is a :class:`_expression.ColumnElement`
  978. subclass which represents a so-called
  979. "placeholder" value in a SQL expression, the value of which is
  980. supplied at the point at which the statement in executed against a
  981. database connection.
  982. In SQLAlchemy, the :func:`.bindparam` construct has
  983. the ability to carry along the actual value that will be ultimately
  984. used at expression time. In this way, it serves not just as
  985. a "placeholder" for eventual population, but also as a means of
  986. representing so-called "unsafe" values which should not be rendered
  987. directly in a SQL statement, but rather should be passed along
  988. to the :term:`DBAPI` as values which need to be correctly escaped
  989. and potentially handled for type-safety.
  990. When using :func:`.bindparam` explicitly, the use case is typically
  991. one of traditional deferment of parameters; the :func:`.bindparam`
  992. construct accepts a name which can then be referred to at execution
  993. time::
  994. from sqlalchemy import bindparam
  995. stmt = select(users_table).\
  996. where(users_table.c.name == bindparam('username'))
  997. The above statement, when rendered, will produce SQL similar to::
  998. SELECT id, name FROM user WHERE name = :username
  999. In order to populate the value of ``:username`` above, the value
  1000. would typically be applied at execution time to a method
  1001. like :meth:`_engine.Connection.execute`::
  1002. result = connection.execute(stmt, username='wendy')
  1003. Explicit use of :func:`.bindparam` is also common when producing
  1004. UPDATE or DELETE statements that are to be invoked multiple times,
  1005. where the WHERE criterion of the statement is to change on each
  1006. invocation, such as::
  1007. stmt = (users_table.update().
  1008. where(user_table.c.name == bindparam('username')).
  1009. values(fullname=bindparam('fullname'))
  1010. )
  1011. connection.execute(
  1012. stmt, [{"username": "wendy", "fullname": "Wendy Smith"},
  1013. {"username": "jack", "fullname": "Jack Jones"},
  1014. ]
  1015. )
  1016. SQLAlchemy's Core expression system makes wide use of
  1017. :func:`.bindparam` in an implicit sense. It is typical that Python
  1018. literal values passed to virtually all SQL expression functions are
  1019. coerced into fixed :func:`.bindparam` constructs. For example, given
  1020. a comparison operation such as::
  1021. expr = users_table.c.name == 'Wendy'
  1022. The above expression will produce a :class:`.BinaryExpression`
  1023. construct, where the left side is the :class:`_schema.Column` object
  1024. representing the ``name`` column, and the right side is a
  1025. :class:`.BindParameter` representing the literal value::
  1026. print(repr(expr.right))
  1027. BindParameter('%(4327771088 name)s', 'Wendy', type_=String())
  1028. The expression above will render SQL such as::
  1029. user.name = :name_1
  1030. Where the ``:name_1`` parameter name is an anonymous name. The
  1031. actual string ``Wendy`` is not in the rendered string, but is carried
  1032. along where it is later used within statement execution. If we
  1033. invoke a statement like the following::
  1034. stmt = select(users_table).where(users_table.c.name == 'Wendy')
  1035. result = connection.execute(stmt)
  1036. We would see SQL logging output as::
  1037. SELECT "user".id, "user".name
  1038. FROM "user"
  1039. WHERE "user".name = %(name_1)s
  1040. {'name_1': 'Wendy'}
  1041. Above, we see that ``Wendy`` is passed as a parameter to the database,
  1042. while the placeholder ``:name_1`` is rendered in the appropriate form
  1043. for the target database, in this case the PostgreSQL database.
  1044. Similarly, :func:`.bindparam` is invoked automatically when working
  1045. with :term:`CRUD` statements as far as the "VALUES" portion is
  1046. concerned. The :func:`_expression.insert` construct produces an
  1047. ``INSERT`` expression which will, at statement execution time, generate
  1048. bound placeholders based on the arguments passed, as in::
  1049. stmt = users_table.insert()
  1050. result = connection.execute(stmt, name='Wendy')
  1051. The above will produce SQL output as::
  1052. INSERT INTO "user" (name) VALUES (%(name)s)
  1053. {'name': 'Wendy'}
  1054. The :class:`_expression.Insert` construct, at
  1055. compilation/execution time, rendered a single :func:`.bindparam`
  1056. mirroring the column name ``name`` as a result of the single ``name``
  1057. parameter we passed to the :meth:`_engine.Connection.execute` method.
  1058. :param key:
  1059. the key (e.g. the name) for this bind param.
  1060. Will be used in the generated
  1061. SQL statement for dialects that use named parameters. This
  1062. value may be modified when part of a compilation operation,
  1063. if other :class:`BindParameter` objects exist with the same
  1064. key, or if its length is too long and truncation is
  1065. required.
  1066. :param value:
  1067. Initial value for this bind param. Will be used at statement
  1068. execution time as the value for this parameter passed to the
  1069. DBAPI, if no other value is indicated to the statement execution
  1070. method for this particular parameter name. Defaults to ``None``.
  1071. :param callable\_:
  1072. A callable function that takes the place of "value". The function
  1073. will be called at statement execution time to determine the
  1074. ultimate value. Used for scenarios where the actual bind
  1075. value cannot be determined at the point at which the clause
  1076. construct is created, but embedded bind values are still desirable.
  1077. :param type\_:
  1078. A :class:`.TypeEngine` class or instance representing an optional
  1079. datatype for this :func:`.bindparam`. If not passed, a type
  1080. may be determined automatically for the bind, based on the given
  1081. value; for example, trivial Python types such as ``str``,
  1082. ``int``, ``bool``
  1083. may result in the :class:`.String`, :class:`.Integer` or
  1084. :class:`.Boolean` types being automatically selected.
  1085. The type of a :func:`.bindparam` is significant especially in that
  1086. the type will apply pre-processing to the value before it is
  1087. passed to the database. For example, a :func:`.bindparam` which
  1088. refers to a datetime value, and is specified as holding the
  1089. :class:`.DateTime` type, may apply conversion needed to the
  1090. value (such as stringification on SQLite) before passing the value
  1091. to the database.
  1092. :param unique:
  1093. if True, the key name of this :class:`.BindParameter` will be
  1094. modified if another :class:`.BindParameter` of the same name
  1095. already has been located within the containing
  1096. expression. This flag is used generally by the internals
  1097. when producing so-called "anonymous" bound expressions, it
  1098. isn't generally applicable to explicitly-named :func:`.bindparam`
  1099. constructs.
  1100. :param required:
  1101. If ``True``, a value is required at execution time. If not passed,
  1102. it defaults to ``True`` if neither :paramref:`.bindparam.value`
  1103. or :paramref:`.bindparam.callable` were passed. If either of these
  1104. parameters are present, then :paramref:`.bindparam.required`
  1105. defaults to ``False``.
  1106. :param quote:
  1107. True if this parameter name requires quoting and is not
  1108. currently known as a SQLAlchemy reserved word; this currently
  1109. only applies to the Oracle backend, where bound names must
  1110. sometimes be quoted.
  1111. :param isoutparam:
  1112. if True, the parameter should be treated like a stored procedure
  1113. "OUT" parameter. This applies to backends such as Oracle which
  1114. support OUT parameters.
  1115. :param expanding:
  1116. if True, this parameter will be treated as an "expanding" parameter
  1117. at execution time; the parameter value is expected to be a sequence,
  1118. rather than a scalar value, and the string SQL statement will
  1119. be transformed on a per-execution basis to accommodate the sequence
  1120. with a variable number of parameter slots passed to the DBAPI.
  1121. This is to allow statement caching to be used in conjunction with
  1122. an IN clause.
  1123. .. seealso::
  1124. :meth:`.ColumnOperators.in_`
  1125. :ref:`baked_in` - with baked queries
  1126. .. note:: The "expanding" feature does not support "executemany"-
  1127. style parameter sets.
  1128. .. versionadded:: 1.2
  1129. .. versionchanged:: 1.3 the "expanding" bound parameter feature now
  1130. supports empty lists.
  1131. .. seealso::
  1132. :ref:`coretutorial_bind_param`
  1133. :ref:`coretutorial_insert_expressions`
  1134. :func:`.outparam`
  1135. :param literal_execute:
  1136. if True, the bound parameter will be rendered in the compile phase
  1137. with a special "POSTCOMPILE" token, and the SQLAlchemy compiler will
  1138. render the final value of the parameter into the SQL statement at
  1139. statement execution time, omitting the value from the parameter
  1140. dictionary / list passed to DBAPI ``cursor.execute()``. This
  1141. produces a similar effect as that of using the ``literal_binds``,
  1142. compilation flag, however takes place as the statement is sent to
  1143. the DBAPI ``cursor.execute()`` method, rather than when the statement
  1144. is compiled. The primary use of this
  1145. capability is for rendering LIMIT / OFFSET clauses for database
  1146. drivers that can't accommodate for bound parameters in these
  1147. contexts, while allowing SQL constructs to be cacheable at the
  1148. compilation level.
  1149. .. versionadded:: 1.4 Added "post compile" bound parameters
  1150. .. seealso::
  1151. :ref:`change_4808`.
  1152. """
  1153. if required is NO_ARG:
  1154. required = value is NO_ARG and callable_ is None
  1155. if value is NO_ARG:
  1156. value = None
  1157. if quote is not None:
  1158. key = quoted_name(key, quote)
  1159. if unique:
  1160. self.key = _anonymous_label.safe_construct(
  1161. id(self),
  1162. key
  1163. if key is not None and not isinstance(key, _anonymous_label)
  1164. else "param",
  1165. sanitize_key=True,
  1166. )
  1167. self._key_is_anon = True
  1168. elif key:
  1169. self.key = key
  1170. else:
  1171. self.key = _anonymous_label.safe_construct(id(self), "param")
  1172. self._key_is_anon = True
  1173. # identifying key that won't change across
  1174. # clones, used to identify the bind's logical
  1175. # identity
  1176. self._identifying_key = self.key
  1177. # key that was passed in the first place, used to
  1178. # generate new keys
  1179. self._orig_key = key or "param"
  1180. self.unique = unique
  1181. self.value = value
  1182. self.callable = callable_
  1183. self.isoutparam = isoutparam
  1184. self.required = required
  1185. # indicate an "expanding" parameter; the compiler sets this
  1186. # automatically in the compiler _render_in_expr_w_bindparam method
  1187. # for an IN expression
  1188. self.expanding = expanding
  1189. # this is another hint to help w/ expanding and is typically
  1190. # set in the compiler _render_in_expr_w_bindparam method for an
  1191. # IN expression
  1192. self.expand_op = None
  1193. self.literal_execute = literal_execute
  1194. if _is_crud:
  1195. self._is_crud = True
  1196. if type_ is None:
  1197. if expanding and value:
  1198. check_value = value[0]
  1199. else:
  1200. check_value = value
  1201. if _compared_to_type is not None:
  1202. self.type = _compared_to_type.coerce_compared_value(
  1203. _compared_to_operator, check_value
  1204. )
  1205. else:
  1206. self.type = type_api._resolve_value_to_type(check_value)
  1207. elif isinstance(type_, type):
  1208. self.type = type_()
  1209. elif type_._is_tuple_type and value:
  1210. if expanding:
  1211. check_value = value[0]
  1212. else:
  1213. check_value = value
  1214. self.type = type_._resolve_values_to_types(check_value)
  1215. else:
  1216. self.type = type_
  1217. def _with_value(self, value, maintain_key=False, required=NO_ARG):
  1218. """Return a copy of this :class:`.BindParameter` with the given value
  1219. set.
  1220. """
  1221. cloned = self._clone(maintain_key=maintain_key)
  1222. cloned.value = value
  1223. cloned.callable = None
  1224. cloned.required = required if required is not NO_ARG else self.required
  1225. if cloned.type is type_api.NULLTYPE:
  1226. cloned.type = type_api._resolve_value_to_type(value)
  1227. return cloned
  1228. @property
  1229. def effective_value(self):
  1230. """Return the value of this bound parameter,
  1231. taking into account if the ``callable`` parameter
  1232. was set.
  1233. The ``callable`` value will be evaluated
  1234. and returned if present, else ``value``.
  1235. """
  1236. if self.callable:
  1237. return self.callable()
  1238. else:
  1239. return self.value
  1240. def render_literal_execute(self):
  1241. """Produce a copy of this bound parameter that will enable the
  1242. :paramref:`_sql.BindParameter.literal_execute` flag.
  1243. The :paramref:`_sql.BindParameter.literal_execute` flag will
  1244. have the effect of the parameter rendered in the compiled SQL
  1245. string using ``[POSTCOMPILE]`` form, which is a special form that
  1246. is converted to be a rendering of the literal value of the parameter
  1247. at SQL execution time. The rationale is to support caching
  1248. of SQL statement strings that can embed per-statement literal values,
  1249. such as LIMIT and OFFSET parameters, in the final SQL string that
  1250. is passed to the DBAPI. Dialects in particular may want to use
  1251. this method within custom compilation schemes.
  1252. .. versionadded:: 1.4.5
  1253. .. seealso::
  1254. :ref:`engine_thirdparty_caching`
  1255. """
  1256. return self.__class__(
  1257. self.key,
  1258. self.value,
  1259. type_=self.type,
  1260. literal_execute=True,
  1261. )
  1262. def _negate_in_binary(self, negated_op, original_op):
  1263. if self.expand_op is original_op:
  1264. bind = self._clone()
  1265. bind.expand_op = negated_op
  1266. return bind
  1267. else:
  1268. return self
  1269. def _with_binary_element_type(self, type_):
  1270. c = ClauseElement._clone(self)
  1271. c.type = type_
  1272. return c
  1273. def _clone(self, maintain_key=False, **kw):
  1274. c = ClauseElement._clone(self, **kw)
  1275. if not maintain_key and self.unique:
  1276. c.key = _anonymous_label.safe_construct(
  1277. id(c), c._orig_key or "param", sanitize_key=True
  1278. )
  1279. return c
  1280. def _gen_cache_key(self, anon_map, bindparams):
  1281. _gen_cache_ok = self.__class__.__dict__.get("inherit_cache", False)
  1282. if not _gen_cache_ok:
  1283. if anon_map is not None:
  1284. anon_map[NO_CACHE] = True
  1285. return None
  1286. idself = id(self)
  1287. if idself in anon_map:
  1288. return (anon_map[idself], self.__class__)
  1289. else:
  1290. # inline of
  1291. # id_ = anon_map[idself]
  1292. anon_map[idself] = id_ = str(anon_map.index)
  1293. anon_map.index += 1
  1294. if bindparams is not None:
  1295. bindparams.append(self)
  1296. return (
  1297. id_,
  1298. self.__class__,
  1299. self.type._static_cache_key,
  1300. self.key % anon_map if self._key_is_anon else self.key,
  1301. )
  1302. def _convert_to_unique(self):
  1303. if not self.unique:
  1304. self.unique = True
  1305. self.key = _anonymous_label.safe_construct(
  1306. id(self), self._orig_key or "param", sanitize_key=True
  1307. )
  1308. def __getstate__(self):
  1309. """execute a deferred value for serialization purposes."""
  1310. d = self.__dict__.copy()
  1311. v = self.value
  1312. if self.callable:
  1313. v = self.callable()
  1314. d["callable"] = None
  1315. d["value"] = v
  1316. return d
  1317. def __setstate__(self, state):
  1318. if state.get("unique", False):
  1319. state["key"] = _anonymous_label.safe_construct(
  1320. id(self), state.get("_orig_key", "param"), sanitize_key=True
  1321. )
  1322. self.__dict__.update(state)
  1323. def __repr__(self):
  1324. return "%s(%r, %r, type_=%r)" % (
  1325. self.__class__.__name__,
  1326. self.key,
  1327. self.value,
  1328. self.type,
  1329. )
  1330. class TypeClause(ClauseElement):
  1331. """Handle a type keyword in a SQL statement.
  1332. Used by the ``Case`` statement.
  1333. """
  1334. __visit_name__ = "typeclause"
  1335. _traverse_internals = [("type", InternalTraversal.dp_type)]
  1336. def __init__(self, type_):
  1337. self.type = type_
  1338. class TextClause(
  1339. roles.DDLConstraintColumnRole,
  1340. roles.DDLExpressionRole,
  1341. roles.StatementOptionRole,
  1342. roles.WhereHavingRole,
  1343. roles.OrderByRole,
  1344. roles.FromClauseRole,
  1345. roles.SelectStatementRole,
  1346. roles.BinaryElementRole,
  1347. roles.InElementRole,
  1348. Executable,
  1349. ClauseElement,
  1350. ):
  1351. """Represent a literal SQL text fragment.
  1352. E.g.::
  1353. from sqlalchemy import text
  1354. t = text("SELECT * FROM users")
  1355. result = connection.execute(t)
  1356. The :class:`_expression.TextClause` construct is produced using the
  1357. :func:`_expression.text`
  1358. function; see that function for full documentation.
  1359. .. seealso::
  1360. :func:`_expression.text`
  1361. """
  1362. __visit_name__ = "textclause"
  1363. _traverse_internals = [
  1364. ("_bindparams", InternalTraversal.dp_string_clauseelement_dict),
  1365. ("text", InternalTraversal.dp_string),
  1366. ]
  1367. _is_text_clause = True
  1368. _is_textual = True
  1369. _bind_params_regex = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)", re.UNICODE)
  1370. _execution_options = Executable._execution_options.union(
  1371. {"autocommit": PARSE_AUTOCOMMIT}
  1372. )
  1373. _is_implicitly_boolean = False
  1374. _render_label_in_columns_clause = False
  1375. _hide_froms = ()
  1376. def __and__(self, other):
  1377. # support use in select.where(), query.filter()
  1378. return and_(self, other)
  1379. @property
  1380. def _select_iterable(self):
  1381. return (self,)
  1382. # help in those cases where text() is
  1383. # interpreted in a column expression situation
  1384. key = _label = None
  1385. _allow_label_resolve = False
  1386. def __init__(self, text, bind=None):
  1387. self._bind = bind
  1388. self._bindparams = {}
  1389. def repl(m):
  1390. self._bindparams[m.group(1)] = BindParameter(m.group(1))
  1391. return ":%s" % m.group(1)
  1392. # scan the string and search for bind parameter names, add them
  1393. # to the list of bindparams
  1394. self.text = self._bind_params_regex.sub(repl, text)
  1395. @classmethod
  1396. @_document_text_coercion("text", ":func:`.text`", ":paramref:`.text.text`")
  1397. @util.deprecated_params(
  1398. bind=(
  1399. "2.0",
  1400. "The :paramref:`_sql.text.bind` argument is deprecated and "
  1401. "will be removed in SQLAlchemy 2.0.",
  1402. ),
  1403. )
  1404. def _create_text(cls, text, bind=None):
  1405. r"""Construct a new :class:`_expression.TextClause` clause,
  1406. representing
  1407. a textual SQL string directly.
  1408. E.g.::
  1409. from sqlalchemy import text
  1410. t = text("SELECT * FROM users")
  1411. result = connection.execute(t)
  1412. The advantages :func:`_expression.text`
  1413. provides over a plain string are
  1414. backend-neutral support for bind parameters, per-statement
  1415. execution options, as well as
  1416. bind parameter and result-column typing behavior, allowing
  1417. SQLAlchemy type constructs to play a role when executing
  1418. a statement that is specified literally. The construct can also
  1419. be provided with a ``.c`` collection of column elements, allowing
  1420. it to be embedded in other SQL expression constructs as a subquery.
  1421. Bind parameters are specified by name, using the format ``:name``.
  1422. E.g.::
  1423. t = text("SELECT * FROM users WHERE id=:user_id")
  1424. result = connection.execute(t, user_id=12)
  1425. For SQL statements where a colon is required verbatim, as within
  1426. an inline string, use a backslash to escape::
  1427. t = text("SELECT * FROM users WHERE name='\:username'")
  1428. The :class:`_expression.TextClause`
  1429. construct includes methods which can
  1430. provide information about the bound parameters as well as the column
  1431. values which would be returned from the textual statement, assuming
  1432. it's an executable SELECT type of statement. The
  1433. :meth:`_expression.TextClause.bindparams`
  1434. method is used to provide bound
  1435. parameter detail, and :meth:`_expression.TextClause.columns`
  1436. method allows
  1437. specification of return columns including names and types::
  1438. t = text("SELECT * FROM users WHERE id=:user_id").\
  1439. bindparams(user_id=7).\
  1440. columns(id=Integer, name=String)
  1441. for id, name in connection.execute(t):
  1442. print(id, name)
  1443. The :func:`_expression.text` construct is used in cases when
  1444. a literal string SQL fragment is specified as part of a larger query,
  1445. such as for the WHERE clause of a SELECT statement::
  1446. s = select(users.c.id, users.c.name).where(text("id=:user_id"))
  1447. result = connection.execute(s, user_id=12)
  1448. :func:`_expression.text` is also used for the construction
  1449. of a full, standalone statement using plain text.
  1450. As such, SQLAlchemy refers
  1451. to it as an :class:`.Executable` object, and it supports
  1452. the :meth:`Executable.execution_options` method. For example,
  1453. a :func:`_expression.text`
  1454. construct that should be subject to "autocommit"
  1455. can be set explicitly so using the
  1456. :paramref:`.Connection.execution_options.autocommit` option::
  1457. t = text("EXEC my_procedural_thing()").\
  1458. execution_options(autocommit=True)
  1459. .. deprecated:: 1.4 The "autocommit" execution option is deprecated
  1460. and will be removed in SQLAlchemy 2.0. See
  1461. :ref:`migration_20_autocommit` for discussion.
  1462. :param text:
  1463. the text of the SQL statement to be created. Use ``:<param>``
  1464. to specify bind parameters; they will be compiled to their
  1465. engine-specific format.
  1466. :param bind:
  1467. an optional connection or engine to be used for this text query.
  1468. .. seealso::
  1469. :ref:`sqlexpression_text` - in the Core tutorial
  1470. """
  1471. return TextClause(text, bind=bind)
  1472. @_generative
  1473. def bindparams(self, *binds, **names_to_values):
  1474. """Establish the values and/or types of bound parameters within
  1475. this :class:`_expression.TextClause` construct.
  1476. Given a text construct such as::
  1477. from sqlalchemy import text
  1478. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1479. "AND timestamp=:timestamp")
  1480. the :meth:`_expression.TextClause.bindparams`
  1481. method can be used to establish
  1482. the initial value of ``:name`` and ``:timestamp``,
  1483. using simple keyword arguments::
  1484. stmt = stmt.bindparams(name='jack',
  1485. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1486. Where above, new :class:`.BindParameter` objects
  1487. will be generated with the names ``name`` and ``timestamp``, and
  1488. values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,
  1489. respectively. The types will be
  1490. inferred from the values given, in this case :class:`.String` and
  1491. :class:`.DateTime`.
  1492. When specific typing behavior is needed, the positional ``*binds``
  1493. argument can be used in which to specify :func:`.bindparam` constructs
  1494. directly. These constructs must include at least the ``key``
  1495. argument, then an optional value and type::
  1496. from sqlalchemy import bindparam
  1497. stmt = stmt.bindparams(
  1498. bindparam('name', value='jack', type_=String),
  1499. bindparam('timestamp', type_=DateTime)
  1500. )
  1501. Above, we specified the type of :class:`.DateTime` for the
  1502. ``timestamp`` bind, and the type of :class:`.String` for the ``name``
  1503. bind. In the case of ``name`` we also set the default value of
  1504. ``"jack"``.
  1505. Additional bound parameters can be supplied at statement execution
  1506. time, e.g.::
  1507. result = connection.execute(stmt,
  1508. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1509. The :meth:`_expression.TextClause.bindparams`
  1510. method can be called repeatedly,
  1511. where it will re-use existing :class:`.BindParameter` objects to add
  1512. new information. For example, we can call
  1513. :meth:`_expression.TextClause.bindparams`
  1514. first with typing information, and a
  1515. second time with value information, and it will be combined::
  1516. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1517. "AND timestamp=:timestamp")
  1518. stmt = stmt.bindparams(
  1519. bindparam('name', type_=String),
  1520. bindparam('timestamp', type_=DateTime)
  1521. )
  1522. stmt = stmt.bindparams(
  1523. name='jack',
  1524. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
  1525. )
  1526. The :meth:`_expression.TextClause.bindparams`
  1527. method also supports the concept of
  1528. **unique** bound parameters. These are parameters that are
  1529. "uniquified" on name at statement compilation time, so that multiple
  1530. :func:`_expression.text`
  1531. constructs may be combined together without the names
  1532. conflicting. To use this feature, specify the
  1533. :paramref:`.BindParameter.unique` flag on each :func:`.bindparam`
  1534. object::
  1535. stmt1 = text("select id from table where name=:name").bindparams(
  1536. bindparam("name", value='name1', unique=True)
  1537. )
  1538. stmt2 = text("select id from table where name=:name").bindparams(
  1539. bindparam("name", value='name2', unique=True)
  1540. )
  1541. union = union_all(
  1542. stmt1.columns(column("id")),
  1543. stmt2.columns(column("id"))
  1544. )
  1545. The above statement will render as::
  1546. select id from table where name=:name_1
  1547. UNION ALL select id from table where name=:name_2
  1548. .. versionadded:: 1.3.11 Added support for the
  1549. :paramref:`.BindParameter.unique` flag to work with
  1550. :func:`_expression.text`
  1551. constructs.
  1552. """
  1553. self._bindparams = new_params = self._bindparams.copy()
  1554. for bind in binds:
  1555. try:
  1556. # the regex used for text() currently will not match
  1557. # a unique/anonymous key in any case, so use the _orig_key
  1558. # so that a text() construct can support unique parameters
  1559. existing = new_params[bind._orig_key]
  1560. except KeyError as err:
  1561. util.raise_(
  1562. exc.ArgumentError(
  1563. "This text() construct doesn't define a "
  1564. "bound parameter named %r" % bind._orig_key
  1565. ),
  1566. replace_context=err,
  1567. )
  1568. else:
  1569. new_params[existing._orig_key] = bind
  1570. for key, value in names_to_values.items():
  1571. try:
  1572. existing = new_params[key]
  1573. except KeyError as err:
  1574. util.raise_(
  1575. exc.ArgumentError(
  1576. "This text() construct doesn't define a "
  1577. "bound parameter named %r" % key
  1578. ),
  1579. replace_context=err,
  1580. )
  1581. else:
  1582. new_params[key] = existing._with_value(value, required=False)
  1583. @util.preload_module("sqlalchemy.sql.selectable")
  1584. def columns(self, *cols, **types):
  1585. r"""Turn this :class:`_expression.TextClause` object into a
  1586. :class:`_expression.TextualSelect`
  1587. object that serves the same role as a SELECT
  1588. statement.
  1589. The :class:`_expression.TextualSelect` is part of the
  1590. :class:`_expression.SelectBase`
  1591. hierarchy and can be embedded into another statement by using the
  1592. :meth:`_expression.TextualSelect.subquery` method to produce a
  1593. :class:`.Subquery`
  1594. object, which can then be SELECTed from.
  1595. This function essentially bridges the gap between an entirely
  1596. textual SELECT statement and the SQL expression language concept
  1597. of a "selectable"::
  1598. from sqlalchemy.sql import column, text
  1599. stmt = text("SELECT id, name FROM some_table")
  1600. stmt = stmt.columns(column('id'), column('name')).subquery('st')
  1601. stmt = select(mytable).\
  1602. select_from(
  1603. mytable.join(stmt, mytable.c.name == stmt.c.name)
  1604. ).where(stmt.c.id > 5)
  1605. Above, we pass a series of :func:`_expression.column` elements to the
  1606. :meth:`_expression.TextClause.columns` method positionally. These
  1607. :func:`_expression.column`
  1608. elements now become first class elements upon the
  1609. :attr:`_expression.TextualSelect.selected_columns` column collection,
  1610. which then
  1611. become part of the :attr:`.Subquery.c` collection after
  1612. :meth:`_expression.TextualSelect.subquery` is invoked.
  1613. The column expressions we pass to
  1614. :meth:`_expression.TextClause.columns` may
  1615. also be typed; when we do so, these :class:`.TypeEngine` objects become
  1616. the effective return type of the column, so that SQLAlchemy's
  1617. result-set-processing systems may be used on the return values.
  1618. This is often needed for types such as date or boolean types, as well
  1619. as for unicode processing on some dialect configurations::
  1620. stmt = text("SELECT id, name, timestamp FROM some_table")
  1621. stmt = stmt.columns(
  1622. column('id', Integer),
  1623. column('name', Unicode),
  1624. column('timestamp', DateTime)
  1625. )
  1626. for id, name, timestamp in connection.execute(stmt):
  1627. print(id, name, timestamp)
  1628. As a shortcut to the above syntax, keyword arguments referring to
  1629. types alone may be used, if only type conversion is needed::
  1630. stmt = text("SELECT id, name, timestamp FROM some_table")
  1631. stmt = stmt.columns(
  1632. id=Integer,
  1633. name=Unicode,
  1634. timestamp=DateTime
  1635. )
  1636. for id, name, timestamp in connection.execute(stmt):
  1637. print(id, name, timestamp)
  1638. The positional form of :meth:`_expression.TextClause.columns`
  1639. also provides the
  1640. unique feature of **positional column targeting**, which is
  1641. particularly useful when using the ORM with complex textual queries. If
  1642. we specify the columns from our model to
  1643. :meth:`_expression.TextClause.columns`,
  1644. the result set will match to those columns positionally, meaning the
  1645. name or origin of the column in the textual SQL doesn't matter::
  1646. stmt = text("SELECT users.id, addresses.id, users.id, "
  1647. "users.name, addresses.email_address AS email "
  1648. "FROM users JOIN addresses ON users.id=addresses.user_id "
  1649. "WHERE users.id = 1").columns(
  1650. User.id,
  1651. Address.id,
  1652. Address.user_id,
  1653. User.name,
  1654. Address.email_address
  1655. )
  1656. query = session.query(User).from_statement(stmt).options(
  1657. contains_eager(User.addresses))
  1658. .. versionadded:: 1.1 the :meth:`_expression.TextClause.columns`
  1659. method now
  1660. offers positional column targeting in the result set when
  1661. the column expressions are passed purely positionally.
  1662. The :meth:`_expression.TextClause.columns` method provides a direct
  1663. route to calling :meth:`_expression.FromClause.subquery` as well as
  1664. :meth:`_expression.SelectBase.cte`
  1665. against a textual SELECT statement::
  1666. stmt = stmt.columns(id=Integer, name=String).cte('st')
  1667. stmt = select(sometable).where(sometable.c.id == stmt.c.id)
  1668. :param \*cols: A series of :class:`_expression.ColumnElement` objects,
  1669. typically
  1670. :class:`_schema.Column` objects from a :class:`_schema.Table`
  1671. or ORM level
  1672. column-mapped attributes, representing a set of columns that this
  1673. textual string will SELECT from.
  1674. :param \**types: A mapping of string names to :class:`.TypeEngine`
  1675. type objects indicating the datatypes to use for names that are
  1676. SELECTed from the textual string. Prefer to use the ``*cols``
  1677. argument as it also indicates positional ordering.
  1678. """
  1679. selectable = util.preloaded.sql_selectable
  1680. positional_input_cols = [
  1681. ColumnClause(col.key, types.pop(col.key))
  1682. if col.key in types
  1683. else col
  1684. for col in cols
  1685. ]
  1686. keyed_input_cols = [
  1687. ColumnClause(key, type_) for key, type_ in types.items()
  1688. ]
  1689. return selectable.TextualSelect(
  1690. self,
  1691. positional_input_cols + keyed_input_cols,
  1692. positional=bool(positional_input_cols) and not keyed_input_cols,
  1693. )
  1694. @property
  1695. def type(self):
  1696. return type_api.NULLTYPE
  1697. @property
  1698. def comparator(self):
  1699. return self.type.comparator_factory(self)
  1700. def self_group(self, against=None):
  1701. if against is operators.in_op:
  1702. return Grouping(self)
  1703. else:
  1704. return self
  1705. class Null(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1706. """Represent the NULL keyword in a SQL statement.
  1707. :class:`.Null` is accessed as a constant via the
  1708. :func:`.null` function.
  1709. """
  1710. __visit_name__ = "null"
  1711. _traverse_internals = []
  1712. @util.memoized_property
  1713. def type(self):
  1714. return type_api.NULLTYPE
  1715. @classmethod
  1716. def _instance(cls):
  1717. """Return a constant :class:`.Null` construct."""
  1718. return Null()
  1719. Null._create_singleton()
  1720. class False_(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1721. """Represent the ``false`` keyword, or equivalent, in a SQL statement.
  1722. :class:`.False_` is accessed as a constant via the
  1723. :func:`.false` function.
  1724. """
  1725. __visit_name__ = "false"
  1726. _traverse_internals = []
  1727. @util.memoized_property
  1728. def type(self):
  1729. return type_api.BOOLEANTYPE
  1730. def _negate(self):
  1731. return True_()
  1732. @classmethod
  1733. def _instance(cls):
  1734. """Return a :class:`.False_` construct.
  1735. E.g.::
  1736. >>> from sqlalchemy import false
  1737. >>> print(select(t.c.x).where(false()))
  1738. SELECT x FROM t WHERE false
  1739. A backend which does not support true/false constants will render as
  1740. an expression against 1 or 0::
  1741. >>> print(select(t.c.x).where(false()))
  1742. SELECT x FROM t WHERE 0 = 1
  1743. The :func:`.true` and :func:`.false` constants also feature
  1744. "short circuit" operation within an :func:`.and_` or :func:`.or_`
  1745. conjunction::
  1746. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
  1747. SELECT x FROM t WHERE true
  1748. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
  1749. SELECT x FROM t WHERE false
  1750. .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
  1751. better integrated behavior within conjunctions and on dialects
  1752. that don't support true/false constants.
  1753. .. seealso::
  1754. :func:`.true`
  1755. """
  1756. return False_()
  1757. False_._create_singleton()
  1758. class True_(SingletonConstant, roles.ConstExprRole, ColumnElement):
  1759. """Represent the ``true`` keyword, or equivalent, in a SQL statement.
  1760. :class:`.True_` is accessed as a constant via the
  1761. :func:`.true` function.
  1762. """
  1763. __visit_name__ = "true"
  1764. _traverse_internals = []
  1765. @util.memoized_property
  1766. def type(self):
  1767. return type_api.BOOLEANTYPE
  1768. def _negate(self):
  1769. return False_()
  1770. @classmethod
  1771. def _ifnone(cls, other):
  1772. if other is None:
  1773. return cls._instance()
  1774. else:
  1775. return other
  1776. @classmethod
  1777. def _instance(cls):
  1778. """Return a constant :class:`.True_` construct.
  1779. E.g.::
  1780. >>> from sqlalchemy import true
  1781. >>> print(select(t.c.x).where(true()))
  1782. SELECT x FROM t WHERE true
  1783. A backend which does not support true/false constants will render as
  1784. an expression against 1 or 0::
  1785. >>> print(select(t.c.x).where(true()))
  1786. SELECT x FROM t WHERE 1 = 1
  1787. The :func:`.true` and :func:`.false` constants also feature
  1788. "short circuit" operation within an :func:`.and_` or :func:`.or_`
  1789. conjunction::
  1790. >>> print(select(t.c.x).where(or_(t.c.x > 5, true())))
  1791. SELECT x FROM t WHERE true
  1792. >>> print(select(t.c.x).where(and_(t.c.x > 5, false())))
  1793. SELECT x FROM t WHERE false
  1794. .. versionchanged:: 0.9 :func:`.true` and :func:`.false` feature
  1795. better integrated behavior within conjunctions and on dialects
  1796. that don't support true/false constants.
  1797. .. seealso::
  1798. :func:`.false`
  1799. """
  1800. return True_()
  1801. True_._create_singleton()
  1802. class ClauseList(
  1803. roles.InElementRole,
  1804. roles.OrderByRole,
  1805. roles.ColumnsClauseRole,
  1806. roles.DMLColumnRole,
  1807. ClauseElement,
  1808. ):
  1809. """Describe a list of clauses, separated by an operator.
  1810. By default, is comma-separated, such as a column listing.
  1811. """
  1812. __visit_name__ = "clauselist"
  1813. _is_clause_list = True
  1814. _traverse_internals = [
  1815. ("clauses", InternalTraversal.dp_clauseelement_list),
  1816. ("operator", InternalTraversal.dp_operator),
  1817. ]
  1818. def __init__(self, *clauses, **kwargs):
  1819. self.operator = kwargs.pop("operator", operators.comma_op)
  1820. self.group = kwargs.pop("group", True)
  1821. self.group_contents = kwargs.pop("group_contents", True)
  1822. if kwargs.pop("_flatten_sub_clauses", False):
  1823. clauses = util.flatten_iterator(clauses)
  1824. self._text_converter_role = text_converter_role = kwargs.pop(
  1825. "_literal_as_text_role", roles.WhereHavingRole
  1826. )
  1827. if self.group_contents:
  1828. self.clauses = [
  1829. coercions.expect(
  1830. text_converter_role, clause, apply_propagate_attrs=self
  1831. ).self_group(against=self.operator)
  1832. for clause in clauses
  1833. ]
  1834. else:
  1835. self.clauses = [
  1836. coercions.expect(
  1837. text_converter_role, clause, apply_propagate_attrs=self
  1838. )
  1839. for clause in clauses
  1840. ]
  1841. self._is_implicitly_boolean = operators.is_boolean(self.operator)
  1842. @classmethod
  1843. def _construct_raw(cls, operator, clauses=None):
  1844. self = cls.__new__(cls)
  1845. self.clauses = clauses if clauses else []
  1846. self.group = True
  1847. self.operator = operator
  1848. self.group_contents = True
  1849. self._is_implicitly_boolean = False
  1850. return self
  1851. def __iter__(self):
  1852. return iter(self.clauses)
  1853. def __len__(self):
  1854. return len(self.clauses)
  1855. @property
  1856. def _select_iterable(self):
  1857. return itertools.chain.from_iterable(
  1858. [elem._select_iterable for elem in self.clauses]
  1859. )
  1860. def append(self, clause):
  1861. if self.group_contents:
  1862. self.clauses.append(
  1863. coercions.expect(self._text_converter_role, clause).self_group(
  1864. against=self.operator
  1865. )
  1866. )
  1867. else:
  1868. self.clauses.append(
  1869. coercions.expect(self._text_converter_role, clause)
  1870. )
  1871. @property
  1872. def _from_objects(self):
  1873. return list(itertools.chain(*[c._from_objects for c in self.clauses]))
  1874. def self_group(self, against=None):
  1875. if self.group and operators.is_precedent(self.operator, against):
  1876. return Grouping(self)
  1877. else:
  1878. return self
  1879. class BooleanClauseList(ClauseList, ColumnElement):
  1880. __visit_name__ = "clauselist"
  1881. inherit_cache = True
  1882. def __init__(self, *arg, **kw):
  1883. raise NotImplementedError(
  1884. "BooleanClauseList has a private constructor"
  1885. )
  1886. @classmethod
  1887. def _process_clauses_for_boolean(
  1888. cls, operator, continue_on, skip_on, clauses
  1889. ):
  1890. has_continue_on = None
  1891. convert_clauses = []
  1892. against = operators._asbool
  1893. lcc = 0
  1894. for clause in clauses:
  1895. if clause is continue_on:
  1896. # instance of continue_on, like and_(x, y, True, z), store it
  1897. # if we didn't find one already, we will use it if there
  1898. # are no other expressions here.
  1899. has_continue_on = clause
  1900. elif clause is skip_on:
  1901. # instance of skip_on, e.g. and_(x, y, False, z), cancels
  1902. # the rest out
  1903. convert_clauses = [clause]
  1904. lcc = 1
  1905. break
  1906. else:
  1907. if not lcc:
  1908. lcc = 1
  1909. else:
  1910. against = operator
  1911. # technically this would be len(convert_clauses) + 1
  1912. # however this only needs to indicate "greater than one"
  1913. lcc = 2
  1914. convert_clauses.append(clause)
  1915. if not convert_clauses and has_continue_on is not None:
  1916. convert_clauses = [has_continue_on]
  1917. lcc = 1
  1918. return lcc, [c.self_group(against=against) for c in convert_clauses]
  1919. @classmethod
  1920. def _construct(cls, operator, continue_on, skip_on, *clauses, **kw):
  1921. lcc, convert_clauses = cls._process_clauses_for_boolean(
  1922. operator,
  1923. continue_on,
  1924. skip_on,
  1925. [
  1926. coercions.expect(roles.WhereHavingRole, clause)
  1927. for clause in util.coerce_generator_arg(clauses)
  1928. ],
  1929. )
  1930. if lcc > 1:
  1931. # multiple elements. Return regular BooleanClauseList
  1932. # which will link elements against the operator.
  1933. return cls._construct_raw(operator, convert_clauses)
  1934. elif lcc == 1:
  1935. # just one element. return it as a single boolean element,
  1936. # not a list and discard the operator.
  1937. return convert_clauses[0]
  1938. else:
  1939. # no elements period. deprecated use case. return an empty
  1940. # ClauseList construct that generates nothing unless it has
  1941. # elements added to it.
  1942. util.warn_deprecated(
  1943. "Invoking %(name)s() without arguments is deprecated, and "
  1944. "will be disallowed in a future release. For an empty "
  1945. "%(name)s() construct, use %(name)s(%(continue_on)s, *args)."
  1946. % {
  1947. "name": operator.__name__,
  1948. "continue_on": "True"
  1949. if continue_on is True_._singleton
  1950. else "False",
  1951. },
  1952. version="1.4",
  1953. )
  1954. return cls._construct_raw(operator)
  1955. @classmethod
  1956. def _construct_for_whereclause(cls, clauses):
  1957. operator, continue_on, skip_on = (
  1958. operators.and_,
  1959. True_._singleton,
  1960. False_._singleton,
  1961. )
  1962. lcc, convert_clauses = cls._process_clauses_for_boolean(
  1963. operator,
  1964. continue_on,
  1965. skip_on,
  1966. clauses, # these are assumed to be coerced already
  1967. )
  1968. if lcc > 1:
  1969. # multiple elements. Return regular BooleanClauseList
  1970. # which will link elements against the operator.
  1971. return cls._construct_raw(operator, convert_clauses)
  1972. elif lcc == 1:
  1973. # just one element. return it as a single boolean element,
  1974. # not a list and discard the operator.
  1975. return convert_clauses[0]
  1976. else:
  1977. return None
  1978. @classmethod
  1979. def _construct_raw(cls, operator, clauses=None):
  1980. self = cls.__new__(cls)
  1981. self.clauses = clauses if clauses else []
  1982. self.group = True
  1983. self.operator = operator
  1984. self.group_contents = True
  1985. self.type = type_api.BOOLEANTYPE
  1986. self._is_implicitly_boolean = True
  1987. return self
  1988. @classmethod
  1989. def and_(cls, *clauses):
  1990. r"""Produce a conjunction of expressions joined by ``AND``.
  1991. E.g.::
  1992. from sqlalchemy import and_
  1993. stmt = select(users_table).where(
  1994. and_(
  1995. users_table.c.name == 'wendy',
  1996. users_table.c.enrolled == True
  1997. )
  1998. )
  1999. The :func:`.and_` conjunction is also available using the
  2000. Python ``&`` operator (though note that compound expressions
  2001. need to be parenthesized in order to function with Python
  2002. operator precedence behavior)::
  2003. stmt = select(users_table).where(
  2004. (users_table.c.name == 'wendy') &
  2005. (users_table.c.enrolled == True)
  2006. )
  2007. The :func:`.and_` operation is also implicit in some cases;
  2008. the :meth:`_expression.Select.where`
  2009. method for example can be invoked multiple
  2010. times against a statement, which will have the effect of each
  2011. clause being combined using :func:`.and_`::
  2012. stmt = select(users_table).\
  2013. where(users_table.c.name == 'wendy').\
  2014. where(users_table.c.enrolled == True)
  2015. The :func:`.and_` construct must be given at least one positional
  2016. argument in order to be valid; a :func:`.and_` construct with no
  2017. arguments is ambiguous. To produce an "empty" or dynamically
  2018. generated :func:`.and_` expression, from a given list of expressions,
  2019. a "default" element of ``True`` should be specified::
  2020. criteria = and_(True, *expressions)
  2021. The above expression will compile to SQL as the expression ``true``
  2022. or ``1 = 1``, depending on backend, if no other expressions are
  2023. present. If expressions are present, then the ``True`` value is
  2024. ignored as it does not affect the outcome of an AND expression that
  2025. has other elements.
  2026. .. deprecated:: 1.4 The :func:`.and_` element now requires that at
  2027. least one argument is passed; creating the :func:`.and_` construct
  2028. with no arguments is deprecated, and will emit a deprecation warning
  2029. while continuing to produce a blank SQL string.
  2030. .. seealso::
  2031. :func:`.or_`
  2032. """
  2033. return cls._construct(
  2034. operators.and_, True_._singleton, False_._singleton, *clauses
  2035. )
  2036. @classmethod
  2037. def or_(cls, *clauses):
  2038. """Produce a conjunction of expressions joined by ``OR``.
  2039. E.g.::
  2040. from sqlalchemy import or_
  2041. stmt = select(users_table).where(
  2042. or_(
  2043. users_table.c.name == 'wendy',
  2044. users_table.c.name == 'jack'
  2045. )
  2046. )
  2047. The :func:`.or_` conjunction is also available using the
  2048. Python ``|`` operator (though note that compound expressions
  2049. need to be parenthesized in order to function with Python
  2050. operator precedence behavior)::
  2051. stmt = select(users_table).where(
  2052. (users_table.c.name == 'wendy') |
  2053. (users_table.c.name == 'jack')
  2054. )
  2055. The :func:`.or_` construct must be given at least one positional
  2056. argument in order to be valid; a :func:`.or_` construct with no
  2057. arguments is ambiguous. To produce an "empty" or dynamically
  2058. generated :func:`.or_` expression, from a given list of expressions,
  2059. a "default" element of ``False`` should be specified::
  2060. or_criteria = or_(False, *expressions)
  2061. The above expression will compile to SQL as the expression ``false``
  2062. or ``0 = 1``, depending on backend, if no other expressions are
  2063. present. If expressions are present, then the ``False`` value is
  2064. ignored as it does not affect the outcome of an OR expression which
  2065. has other elements.
  2066. .. deprecated:: 1.4 The :func:`.or_` element now requires that at
  2067. least one argument is passed; creating the :func:`.or_` construct
  2068. with no arguments is deprecated, and will emit a deprecation warning
  2069. while continuing to produce a blank SQL string.
  2070. .. seealso::
  2071. :func:`.and_`
  2072. """
  2073. return cls._construct(
  2074. operators.or_, False_._singleton, True_._singleton, *clauses
  2075. )
  2076. @property
  2077. def _select_iterable(self):
  2078. return (self,)
  2079. def self_group(self, against=None):
  2080. if not self.clauses:
  2081. return self
  2082. else:
  2083. return super(BooleanClauseList, self).self_group(against=against)
  2084. def _negate(self):
  2085. return ClauseList._negate(self)
  2086. and_ = BooleanClauseList.and_
  2087. or_ = BooleanClauseList.or_
  2088. class Tuple(ClauseList, ColumnElement):
  2089. """Represent a SQL tuple."""
  2090. __visit_name__ = "tuple"
  2091. _traverse_internals = ClauseList._traverse_internals + []
  2092. @util.preload_module("sqlalchemy.sql.sqltypes")
  2093. def __init__(self, *clauses, **kw):
  2094. """Return a :class:`.Tuple`.
  2095. Main usage is to produce a composite IN construct using
  2096. :meth:`.ColumnOperators.in_` ::
  2097. from sqlalchemy import tuple_
  2098. tuple_(table.c.col1, table.c.col2).in_(
  2099. [(1, 2), (5, 12), (10, 19)]
  2100. )
  2101. .. versionchanged:: 1.3.6 Added support for SQLite IN tuples.
  2102. .. warning::
  2103. The composite IN construct is not supported by all backends, and is
  2104. currently known to work on PostgreSQL, MySQL, and SQLite.
  2105. Unsupported backends will raise a subclass of
  2106. :class:`~sqlalchemy.exc.DBAPIError` when such an expression is
  2107. invoked.
  2108. """
  2109. sqltypes = util.preloaded.sql_sqltypes
  2110. types = kw.pop("types", None)
  2111. if types is None:
  2112. clauses = [
  2113. coercions.expect(roles.ExpressionElementRole, c)
  2114. for c in clauses
  2115. ]
  2116. else:
  2117. if len(types) != len(clauses):
  2118. raise exc.ArgumentError(
  2119. "Wrong number of elements for %d-tuple: %r "
  2120. % (len(types), clauses)
  2121. )
  2122. clauses = [
  2123. coercions.expect(
  2124. roles.ExpressionElementRole,
  2125. c,
  2126. type_=typ if not typ._isnull else None,
  2127. )
  2128. for typ, c in zip(types, clauses)
  2129. ]
  2130. self.type = sqltypes.TupleType(*[arg.type for arg in clauses])
  2131. super(Tuple, self).__init__(*clauses, **kw)
  2132. @property
  2133. def _select_iterable(self):
  2134. return (self,)
  2135. def _bind_param(self, operator, obj, type_=None, expanding=False):
  2136. if expanding:
  2137. return BindParameter(
  2138. None,
  2139. value=obj,
  2140. _compared_to_operator=operator,
  2141. unique=True,
  2142. expanding=True,
  2143. type_=self.type,
  2144. )
  2145. else:
  2146. return Tuple(
  2147. *[
  2148. BindParameter(
  2149. None,
  2150. o,
  2151. _compared_to_operator=operator,
  2152. _compared_to_type=compared_to_type,
  2153. unique=True,
  2154. type_=type_,
  2155. )
  2156. for o, compared_to_type in zip(obj, self.type.types)
  2157. ]
  2158. )
  2159. def self_group(self, against=None):
  2160. # Tuple is parenthesized by definition.
  2161. return self
  2162. class Case(ColumnElement):
  2163. """Represent a ``CASE`` expression.
  2164. :class:`.Case` is produced using the :func:`.case` factory function,
  2165. as in::
  2166. from sqlalchemy import case
  2167. stmt = select(users_table).\
  2168. where(
  2169. case(
  2170. (users_table.c.name == 'wendy', 'W'),
  2171. (users_table.c.name == 'jack', 'J'),
  2172. else_='E'
  2173. )
  2174. )
  2175. Details on :class:`.Case` usage is at :func:`.case`.
  2176. .. seealso::
  2177. :func:`.case`
  2178. """
  2179. __visit_name__ = "case"
  2180. _traverse_internals = [
  2181. ("value", InternalTraversal.dp_clauseelement),
  2182. ("whens", InternalTraversal.dp_clauseelement_tuples),
  2183. ("else_", InternalTraversal.dp_clauseelement),
  2184. ]
  2185. # TODO: for Py2k removal, this will be:
  2186. # def __init__(self, *whens, value=None, else_=None):
  2187. def __init__(self, *whens, **kw):
  2188. r"""Produce a ``CASE`` expression.
  2189. The ``CASE`` construct in SQL is a conditional object that
  2190. acts somewhat analogously to an "if/then" construct in other
  2191. languages. It returns an instance of :class:`.Case`.
  2192. :func:`.case` in its usual form is passed a series of "when"
  2193. constructs, that is, a list of conditions and results as tuples::
  2194. from sqlalchemy import case
  2195. stmt = select(users_table).\
  2196. where(
  2197. case(
  2198. (users_table.c.name == 'wendy', 'W'),
  2199. (users_table.c.name == 'jack', 'J'),
  2200. else_='E'
  2201. )
  2202. )
  2203. The above statement will produce SQL resembling::
  2204. SELECT id, name FROM user
  2205. WHERE CASE
  2206. WHEN (name = :name_1) THEN :param_1
  2207. WHEN (name = :name_2) THEN :param_2
  2208. ELSE :param_3
  2209. END
  2210. When simple equality expressions of several values against a single
  2211. parent column are needed, :func:`.case` also has a "shorthand" format
  2212. used via the
  2213. :paramref:`.case.value` parameter, which is passed a column
  2214. expression to be compared. In this form, the :paramref:`.case.whens`
  2215. parameter is passed as a dictionary containing expressions to be
  2216. compared against keyed to result expressions. The statement below is
  2217. equivalent to the preceding statement::
  2218. stmt = select(users_table).\
  2219. where(
  2220. case(
  2221. {"wendy": "W", "jack": "J"},
  2222. value=users_table.c.name,
  2223. else_='E'
  2224. )
  2225. )
  2226. The values which are accepted as result values in
  2227. :paramref:`.case.whens` as well as with :paramref:`.case.else_` are
  2228. coerced from Python literals into :func:`.bindparam` constructs.
  2229. SQL expressions, e.g. :class:`_expression.ColumnElement` constructs,
  2230. are accepted
  2231. as well. To coerce a literal string expression into a constant
  2232. expression rendered inline, use the :func:`_expression.literal_column`
  2233. construct,
  2234. as in::
  2235. from sqlalchemy import case, literal_column
  2236. case(
  2237. (
  2238. orderline.c.qty > 100,
  2239. literal_column("'greaterthan100'")
  2240. ),
  2241. (
  2242. orderline.c.qty > 10,
  2243. literal_column("'greaterthan10'")
  2244. ),
  2245. else_=literal_column("'lessthan10'")
  2246. )
  2247. The above will render the given constants without using bound
  2248. parameters for the result values (but still for the comparison
  2249. values), as in::
  2250. CASE
  2251. WHEN (orderline.qty > :qty_1) THEN 'greaterthan100'
  2252. WHEN (orderline.qty > :qty_2) THEN 'greaterthan10'
  2253. ELSE 'lessthan10'
  2254. END
  2255. :param \*whens: The criteria to be compared against,
  2256. :paramref:`.case.whens` accepts two different forms, based on
  2257. whether or not :paramref:`.case.value` is used.
  2258. .. versionchanged:: 1.4 the :func:`_sql.case`
  2259. function now accepts the series of WHEN conditions positionally;
  2260. passing the expressions within a list is deprecated.
  2261. In the first form, it accepts a list of 2-tuples; each 2-tuple
  2262. consists of ``(<sql expression>, <value>)``, where the SQL
  2263. expression is a boolean expression and "value" is a resulting value,
  2264. e.g.::
  2265. case(
  2266. (users_table.c.name == 'wendy', 'W'),
  2267. (users_table.c.name == 'jack', 'J')
  2268. )
  2269. In the second form, it accepts a Python dictionary of comparison
  2270. values mapped to a resulting value; this form requires
  2271. :paramref:`.case.value` to be present, and values will be compared
  2272. using the ``==`` operator, e.g.::
  2273. case(
  2274. {"wendy": "W", "jack": "J"},
  2275. value=users_table.c.name
  2276. )
  2277. :param value: An optional SQL expression which will be used as a
  2278. fixed "comparison point" for candidate values within a dictionary
  2279. passed to :paramref:`.case.whens`.
  2280. :param else\_: An optional SQL expression which will be the evaluated
  2281. result of the ``CASE`` construct if all expressions within
  2282. :paramref:`.case.whens` evaluate to false. When omitted, most
  2283. databases will produce a result of NULL if none of the "when"
  2284. expressions evaluate to true.
  2285. """
  2286. if "whens" in kw:
  2287. util.warn_deprecated_20(
  2288. 'The "whens" argument to case() is now passed using '
  2289. "positional style only, not as a keyword argument."
  2290. )
  2291. whens = (kw.pop("whens"),)
  2292. whens = coercions._expression_collection_was_a_list(
  2293. "whens", "case", whens
  2294. )
  2295. try:
  2296. whens = util.dictlike_iteritems(whens)
  2297. except TypeError:
  2298. pass
  2299. value = kw.pop("value", None)
  2300. whenlist = [
  2301. (
  2302. coercions.expect(
  2303. roles.ExpressionElementRole,
  2304. c,
  2305. apply_propagate_attrs=self,
  2306. ).self_group(),
  2307. coercions.expect(roles.ExpressionElementRole, r),
  2308. )
  2309. for (c, r) in whens
  2310. ]
  2311. if whenlist:
  2312. type_ = list(whenlist[-1])[-1].type
  2313. else:
  2314. type_ = None
  2315. if value is None:
  2316. self.value = None
  2317. else:
  2318. self.value = coercions.expect(roles.ExpressionElementRole, value)
  2319. self.type = type_
  2320. self.whens = whenlist
  2321. else_ = kw.pop("else_", None)
  2322. if else_ is not None:
  2323. self.else_ = coercions.expect(roles.ExpressionElementRole, else_)
  2324. else:
  2325. self.else_ = None
  2326. if kw:
  2327. raise TypeError("unknown arguments: %s" % (", ".join(sorted(kw))))
  2328. @property
  2329. def _from_objects(self):
  2330. return list(
  2331. itertools.chain(*[x._from_objects for x in self.get_children()])
  2332. )
  2333. def literal_column(text, type_=None):
  2334. r"""Produce a :class:`.ColumnClause` object that has the
  2335. :paramref:`_expression.column.is_literal` flag set to True.
  2336. :func:`_expression.literal_column` is similar to
  2337. :func:`_expression.column`, except that
  2338. it is more often used as a "standalone" column expression that renders
  2339. exactly as stated; while :func:`_expression.column`
  2340. stores a string name that
  2341. will be assumed to be part of a table and may be quoted as such,
  2342. :func:`_expression.literal_column` can be that,
  2343. or any other arbitrary column-oriented
  2344. expression.
  2345. :param text: the text of the expression; can be any SQL expression.
  2346. Quoting rules will not be applied. To specify a column-name expression
  2347. which should be subject to quoting rules, use the :func:`column`
  2348. function.
  2349. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
  2350. object which will
  2351. provide result-set translation and additional expression semantics for
  2352. this column. If left as ``None`` the type will be :class:`.NullType`.
  2353. .. seealso::
  2354. :func:`_expression.column`
  2355. :func:`_expression.text`
  2356. :ref:`sqlexpression_literal_column`
  2357. """
  2358. return ColumnClause(text, type_=type_, is_literal=True)
  2359. class Cast(WrapsColumnExpression, ColumnElement):
  2360. """Represent a ``CAST`` expression.
  2361. :class:`.Cast` is produced using the :func:`.cast` factory function,
  2362. as in::
  2363. from sqlalchemy import cast, Numeric
  2364. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
  2365. Details on :class:`.Cast` usage is at :func:`.cast`.
  2366. .. seealso::
  2367. :ref:`coretutorial_casts`
  2368. :func:`.cast`
  2369. :func:`.type_coerce` - an alternative to CAST that coerces the type
  2370. on the Python side only, which is often sufficient to generate the
  2371. correct SQL and data coercion.
  2372. """
  2373. __visit_name__ = "cast"
  2374. _traverse_internals = [
  2375. ("clause", InternalTraversal.dp_clauseelement),
  2376. ("typeclause", InternalTraversal.dp_clauseelement),
  2377. ]
  2378. def __init__(self, expression, type_):
  2379. r"""Produce a ``CAST`` expression.
  2380. :func:`.cast` returns an instance of :class:`.Cast`.
  2381. E.g.::
  2382. from sqlalchemy import cast, Numeric
  2383. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
  2384. The above statement will produce SQL resembling::
  2385. SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
  2386. The :func:`.cast` function performs two distinct functions when
  2387. used. The first is that it renders the ``CAST`` expression within
  2388. the resulting SQL string. The second is that it associates the given
  2389. type (e.g. :class:`.TypeEngine` class or instance) with the column
  2390. expression on the Python side, which means the expression will take
  2391. on the expression operator behavior associated with that type,
  2392. as well as the bound-value handling and result-row-handling behavior
  2393. of the type.
  2394. .. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
  2395. to the expression such that it takes effect on the bound-value,
  2396. e.g. the Python-to-database direction, in addition to the
  2397. result handling, e.g. database-to-Python, direction.
  2398. An alternative to :func:`.cast` is the :func:`.type_coerce` function.
  2399. This function performs the second task of associating an expression
  2400. with a specific type, but does not render the ``CAST`` expression
  2401. in SQL.
  2402. :param expression: A SQL expression, such as a
  2403. :class:`_expression.ColumnElement`
  2404. expression or a Python string which will be coerced into a bound
  2405. literal value.
  2406. :param type\_: A :class:`.TypeEngine` class or instance indicating
  2407. the type to which the ``CAST`` should apply.
  2408. .. seealso::
  2409. :ref:`coretutorial_casts`
  2410. :func:`.type_coerce` - an alternative to CAST that coerces the type
  2411. on the Python side only, which is often sufficient to generate the
  2412. correct SQL and data coercion.
  2413. """
  2414. self.type = type_api.to_instance(type_)
  2415. self.clause = coercions.expect(
  2416. roles.ExpressionElementRole,
  2417. expression,
  2418. type_=self.type,
  2419. apply_propagate_attrs=self,
  2420. )
  2421. self.typeclause = TypeClause(self.type)
  2422. @property
  2423. def _from_objects(self):
  2424. return self.clause._from_objects
  2425. @property
  2426. def wrapped_column_expression(self):
  2427. return self.clause
  2428. class TypeCoerce(WrapsColumnExpression, ColumnElement):
  2429. """Represent a Python-side type-coercion wrapper.
  2430. :class:`.TypeCoerce` supplies the :func:`_expression.type_coerce`
  2431. function; see that function for usage details.
  2432. .. versionchanged:: 1.1 The :func:`.type_coerce` function now produces
  2433. a persistent :class:`.TypeCoerce` wrapper object rather than
  2434. translating the given object in place.
  2435. .. seealso::
  2436. :func:`_expression.type_coerce`
  2437. :func:`.cast`
  2438. """
  2439. __visit_name__ = "type_coerce"
  2440. _traverse_internals = [
  2441. ("clause", InternalTraversal.dp_clauseelement),
  2442. ("type", InternalTraversal.dp_type),
  2443. ]
  2444. def __init__(self, expression, type_):
  2445. r"""Associate a SQL expression with a particular type, without rendering
  2446. ``CAST``.
  2447. E.g.::
  2448. from sqlalchemy import type_coerce
  2449. stmt = select(type_coerce(log_table.date_string, StringDateTime()))
  2450. The above construct will produce a :class:`.TypeCoerce` object, which
  2451. does not modify the rendering in any way on the SQL side, with the
  2452. possible exception of a generated label if used in a columns clause
  2453. context::
  2454. SELECT date_string AS date_string FROM log
  2455. When result rows are fetched, the ``StringDateTime`` type processor
  2456. will be applied to result rows on behalf of the ``date_string`` column.
  2457. .. note:: the :func:`.type_coerce` construct does not render any
  2458. SQL syntax of its own, including that it does not imply
  2459. parenthesization. Please use :meth:`.TypeCoerce.self_group`
  2460. if explicit parenthesization is required.
  2461. In order to provide a named label for the expression, use
  2462. :meth:`_expression.ColumnElement.label`::
  2463. stmt = select(
  2464. type_coerce(log_table.date_string, StringDateTime()).label('date')
  2465. )
  2466. A type that features bound-value handling will also have that behavior
  2467. take effect when literal values or :func:`.bindparam` constructs are
  2468. passed to :func:`.type_coerce` as targets.
  2469. For example, if a type implements the
  2470. :meth:`.TypeEngine.bind_expression`
  2471. method or :meth:`.TypeEngine.bind_processor` method or equivalent,
  2472. these functions will take effect at statement compilation/execution
  2473. time when a literal value is passed, as in::
  2474. # bound-value handling of MyStringType will be applied to the
  2475. # literal value "some string"
  2476. stmt = select(type_coerce("some string", MyStringType))
  2477. When using :func:`.type_coerce` with composed expressions, note that
  2478. **parenthesis are not applied**. If :func:`.type_coerce` is being
  2479. used in an operator context where the parenthesis normally present from
  2480. CAST are necessary, use the :meth:`.TypeCoerce.self_group` method::
  2481. >>> some_integer = column("someint", Integer)
  2482. >>> some_string = column("somestr", String)
  2483. >>> expr = type_coerce(some_integer + 5, String) + some_string
  2484. >>> print(expr)
  2485. someint + :someint_1 || somestr
  2486. >>> expr = type_coerce(some_integer + 5, String).self_group() + some_string
  2487. >>> print(expr)
  2488. (someint + :someint_1) || somestr
  2489. :param expression: A SQL expression, such as a
  2490. :class:`_expression.ColumnElement`
  2491. expression or a Python string which will be coerced into a bound
  2492. literal value.
  2493. :param type\_: A :class:`.TypeEngine` class or instance indicating
  2494. the type to which the expression is coerced.
  2495. .. seealso::
  2496. :ref:`coretutorial_casts`
  2497. :func:`.cast`
  2498. """ # noqa
  2499. self.type = type_api.to_instance(type_)
  2500. self.clause = coercions.expect(
  2501. roles.ExpressionElementRole,
  2502. expression,
  2503. type_=self.type,
  2504. apply_propagate_attrs=self,
  2505. )
  2506. @property
  2507. def _from_objects(self):
  2508. return self.clause._from_objects
  2509. @HasMemoized.memoized_attribute
  2510. def typed_expression(self):
  2511. if isinstance(self.clause, BindParameter):
  2512. bp = self.clause._clone()
  2513. bp.type = self.type
  2514. return bp
  2515. else:
  2516. return self.clause
  2517. @property
  2518. def wrapped_column_expression(self):
  2519. return self.clause
  2520. def self_group(self, against=None):
  2521. grouped = self.clause.self_group(against=against)
  2522. if grouped is not self.clause:
  2523. return TypeCoerce(grouped, self.type)
  2524. else:
  2525. return self
  2526. class Extract(ColumnElement):
  2527. """Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""
  2528. __visit_name__ = "extract"
  2529. _traverse_internals = [
  2530. ("expr", InternalTraversal.dp_clauseelement),
  2531. ("field", InternalTraversal.dp_string),
  2532. ]
  2533. def __init__(self, field, expr, **kwargs):
  2534. """Return a :class:`.Extract` construct.
  2535. This is typically available as :func:`.extract`
  2536. as well as ``func.extract`` from the
  2537. :data:`.func` namespace.
  2538. :param field: The field to extract.
  2539. :param expr: A column or Python scalar expression serving as the
  2540. right side of the ``EXTRACT`` expression.
  2541. E.g.::
  2542. from sqlalchemy import extract
  2543. from sqlalchemy import table, column
  2544. logged_table = table("user",
  2545. column("id"),
  2546. column("date_created"),
  2547. )
  2548. stmt = select(logged_table.c.id).where(
  2549. extract("YEAR", logged_table.c.date_created) == 2021
  2550. )
  2551. In the above example, the statement is used to select ids from the
  2552. database where the ``YEAR`` component matches a specific value.
  2553. Similarly, one can also select an extracted component::
  2554. stmt = select(
  2555. extract("YEAR", logged_table.c.date_created)
  2556. ).where(logged_table.c.id == 1)
  2557. The implementation of ``EXTRACT`` may vary across database backends.
  2558. Users are reminded to consult their database documentation.
  2559. """
  2560. self.type = type_api.INTEGERTYPE
  2561. self.field = field
  2562. self.expr = coercions.expect(roles.ExpressionElementRole, expr)
  2563. @property
  2564. def _from_objects(self):
  2565. return self.expr._from_objects
  2566. class _label_reference(ColumnElement):
  2567. """Wrap a column expression as it appears in a 'reference' context.
  2568. This expression is any that includes an _order_by_label_element,
  2569. which is a Label, or a DESC / ASC construct wrapping a Label.
  2570. The production of _label_reference() should occur when an expression
  2571. is added to this context; this includes the ORDER BY or GROUP BY of a
  2572. SELECT statement, as well as a few other places, such as the ORDER BY
  2573. within an OVER clause.
  2574. """
  2575. __visit_name__ = "label_reference"
  2576. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  2577. def __init__(self, element):
  2578. self.element = element
  2579. @property
  2580. def _from_objects(self):
  2581. return ()
  2582. class _textual_label_reference(ColumnElement):
  2583. __visit_name__ = "textual_label_reference"
  2584. _traverse_internals = [("element", InternalTraversal.dp_string)]
  2585. def __init__(self, element):
  2586. self.element = element
  2587. @util.memoized_property
  2588. def _text_clause(self):
  2589. return TextClause._create_text(self.element)
  2590. class UnaryExpression(ColumnElement):
  2591. """Define a 'unary' expression.
  2592. A unary expression has a single column expression
  2593. and an operator. The operator can be placed on the left
  2594. (where it is called the 'operator') or right (where it is called the
  2595. 'modifier') of the column expression.
  2596. :class:`.UnaryExpression` is the basis for several unary operators
  2597. including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`,
  2598. :func:`.nulls_first` and :func:`.nulls_last`.
  2599. """
  2600. __visit_name__ = "unary"
  2601. _traverse_internals = [
  2602. ("element", InternalTraversal.dp_clauseelement),
  2603. ("operator", InternalTraversal.dp_operator),
  2604. ("modifier", InternalTraversal.dp_operator),
  2605. ]
  2606. def __init__(
  2607. self,
  2608. element,
  2609. operator=None,
  2610. modifier=None,
  2611. type_=None,
  2612. wraps_column_expression=False,
  2613. ):
  2614. self.operator = operator
  2615. self.modifier = modifier
  2616. self._propagate_attrs = element._propagate_attrs
  2617. self.element = element.self_group(
  2618. against=self.operator or self.modifier
  2619. )
  2620. self.type = type_api.to_instance(type_)
  2621. self.wraps_column_expression = wraps_column_expression
  2622. @classmethod
  2623. def _create_nulls_first(cls, column):
  2624. """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression.
  2625. :func:`.nulls_first` is intended to modify the expression produced
  2626. by :func:`.asc` or :func:`.desc`, and indicates how NULL values
  2627. should be handled when they are encountered during ordering::
  2628. from sqlalchemy import desc, nulls_first
  2629. stmt = select(users_table).order_by(
  2630. nulls_first(desc(users_table.c.name)))
  2631. The SQL expression from the above would resemble::
  2632. SELECT id, name FROM user ORDER BY name DESC NULLS FIRST
  2633. Like :func:`.asc` and :func:`.desc`, :func:`.nulls_first` is typically
  2634. invoked from the column expression itself using
  2635. :meth:`_expression.ColumnElement.nulls_first`,
  2636. rather than as its standalone
  2637. function version, as in::
  2638. stmt = select(users_table).order_by(
  2639. users_table.c.name.desc().nulls_first())
  2640. .. versionchanged:: 1.4 :func:`.nulls_first` is renamed from
  2641. :func:`.nullsfirst` in previous releases.
  2642. The previous name remains available for backwards compatibility.
  2643. .. seealso::
  2644. :func:`.asc`
  2645. :func:`.desc`
  2646. :func:`.nulls_last`
  2647. :meth:`_expression.Select.order_by`
  2648. """
  2649. return UnaryExpression(
  2650. coercions.expect(roles.ByOfRole, column),
  2651. modifier=operators.nulls_first_op,
  2652. wraps_column_expression=False,
  2653. )
  2654. @classmethod
  2655. def _create_nulls_last(cls, column):
  2656. """Produce the ``NULLS LAST`` modifier for an ``ORDER BY`` expression.
  2657. :func:`.nulls_last` is intended to modify the expression produced
  2658. by :func:`.asc` or :func:`.desc`, and indicates how NULL values
  2659. should be handled when they are encountered during ordering::
  2660. from sqlalchemy import desc, nulls_last
  2661. stmt = select(users_table).order_by(
  2662. nulls_last(desc(users_table.c.name)))
  2663. The SQL expression from the above would resemble::
  2664. SELECT id, name FROM user ORDER BY name DESC NULLS LAST
  2665. Like :func:`.asc` and :func:`.desc`, :func:`.nulls_last` is typically
  2666. invoked from the column expression itself using
  2667. :meth:`_expression.ColumnElement.nulls_last`,
  2668. rather than as its standalone
  2669. function version, as in::
  2670. stmt = select(users_table).order_by(
  2671. users_table.c.name.desc().nulls_last())
  2672. .. versionchanged:: 1.4 :func:`.nulls_last` is renamed from
  2673. :func:`.nullslast` in previous releases.
  2674. The previous name remains available for backwards compatibility.
  2675. .. seealso::
  2676. :func:`.asc`
  2677. :func:`.desc`
  2678. :func:`.nulls_first`
  2679. :meth:`_expression.Select.order_by`
  2680. """
  2681. return UnaryExpression(
  2682. coercions.expect(roles.ByOfRole, column),
  2683. modifier=operators.nulls_last_op,
  2684. wraps_column_expression=False,
  2685. )
  2686. @classmethod
  2687. def _create_desc(cls, column):
  2688. """Produce a descending ``ORDER BY`` clause element.
  2689. e.g.::
  2690. from sqlalchemy import desc
  2691. stmt = select(users_table).order_by(desc(users_table.c.name))
  2692. will produce SQL as::
  2693. SELECT id, name FROM user ORDER BY name DESC
  2694. The :func:`.desc` function is a standalone version of the
  2695. :meth:`_expression.ColumnElement.desc`
  2696. method available on all SQL expressions,
  2697. e.g.::
  2698. stmt = select(users_table).order_by(users_table.c.name.desc())
  2699. :param column: A :class:`_expression.ColumnElement` (e.g.
  2700. scalar SQL expression)
  2701. with which to apply the :func:`.desc` operation.
  2702. .. seealso::
  2703. :func:`.asc`
  2704. :func:`.nulls_first`
  2705. :func:`.nulls_last`
  2706. :meth:`_expression.Select.order_by`
  2707. """
  2708. return UnaryExpression(
  2709. coercions.expect(roles.ByOfRole, column),
  2710. modifier=operators.desc_op,
  2711. wraps_column_expression=False,
  2712. )
  2713. @classmethod
  2714. def _create_asc(cls, column):
  2715. """Produce an ascending ``ORDER BY`` clause element.
  2716. e.g.::
  2717. from sqlalchemy import asc
  2718. stmt = select(users_table).order_by(asc(users_table.c.name))
  2719. will produce SQL as::
  2720. SELECT id, name FROM user ORDER BY name ASC
  2721. The :func:`.asc` function is a standalone version of the
  2722. :meth:`_expression.ColumnElement.asc`
  2723. method available on all SQL expressions,
  2724. e.g.::
  2725. stmt = select(users_table).order_by(users_table.c.name.asc())
  2726. :param column: A :class:`_expression.ColumnElement` (e.g.
  2727. scalar SQL expression)
  2728. with which to apply the :func:`.asc` operation.
  2729. .. seealso::
  2730. :func:`.desc`
  2731. :func:`.nulls_first`
  2732. :func:`.nulls_last`
  2733. :meth:`_expression.Select.order_by`
  2734. """
  2735. return UnaryExpression(
  2736. coercions.expect(roles.ByOfRole, column),
  2737. modifier=operators.asc_op,
  2738. wraps_column_expression=False,
  2739. )
  2740. @classmethod
  2741. def _create_distinct(cls, expr):
  2742. """Produce an column-expression-level unary ``DISTINCT`` clause.
  2743. This applies the ``DISTINCT`` keyword to an individual column
  2744. expression, and is typically contained within an aggregate function,
  2745. as in::
  2746. from sqlalchemy import distinct, func
  2747. stmt = select(func.count(distinct(users_table.c.name)))
  2748. The above would produce an expression resembling::
  2749. SELECT COUNT(DISTINCT name) FROM user
  2750. The :func:`.distinct` function is also available as a column-level
  2751. method, e.g. :meth:`_expression.ColumnElement.distinct`, as in::
  2752. stmt = select(func.count(users_table.c.name.distinct()))
  2753. The :func:`.distinct` operator is different from the
  2754. :meth:`_expression.Select.distinct` method of
  2755. :class:`_expression.Select`,
  2756. which produces a ``SELECT`` statement
  2757. with ``DISTINCT`` applied to the result set as a whole,
  2758. e.g. a ``SELECT DISTINCT`` expression. See that method for further
  2759. information.
  2760. .. seealso::
  2761. :meth:`_expression.ColumnElement.distinct`
  2762. :meth:`_expression.Select.distinct`
  2763. :data:`.func`
  2764. """
  2765. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2766. return UnaryExpression(
  2767. expr,
  2768. operator=operators.distinct_op,
  2769. type_=expr.type,
  2770. wraps_column_expression=False,
  2771. )
  2772. @property
  2773. def _order_by_label_element(self):
  2774. if self.modifier in (operators.desc_op, operators.asc_op):
  2775. return self.element._order_by_label_element
  2776. else:
  2777. return None
  2778. @property
  2779. def _from_objects(self):
  2780. return self.element._from_objects
  2781. def _negate(self):
  2782. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  2783. return UnaryExpression(
  2784. self.self_group(against=operators.inv),
  2785. operator=operators.inv,
  2786. type_=type_api.BOOLEANTYPE,
  2787. wraps_column_expression=self.wraps_column_expression,
  2788. )
  2789. else:
  2790. return ClauseElement._negate(self)
  2791. def self_group(self, against=None):
  2792. if self.operator and operators.is_precedent(self.operator, against):
  2793. return Grouping(self)
  2794. else:
  2795. return self
  2796. class CollectionAggregate(UnaryExpression):
  2797. """Forms the basis for right-hand collection operator modifiers
  2798. ANY and ALL.
  2799. The ANY and ALL keywords are available in different ways on different
  2800. backends. On PostgreSQL, they only work for an ARRAY type. On
  2801. MySQL, they only work for subqueries.
  2802. """
  2803. inherit_cache = True
  2804. @classmethod
  2805. def _create_any(cls, expr):
  2806. """Produce an ANY expression.
  2807. For dialects such as that of PostgreSQL, this operator applies
  2808. to usage of the :class:`_types.ARRAY` datatype, for that of
  2809. MySQL, it may apply to a subquery. e.g.::
  2810. # renders on PostgreSQL:
  2811. # '5 = ANY (somearray)'
  2812. expr = 5 == any_(mytable.c.somearray)
  2813. # renders on MySQL:
  2814. # '5 = ANY (SELECT value FROM table)'
  2815. expr = 5 == any_(select(table.c.value))
  2816. Comparison to NULL may work using ``None`` or :func:`_sql.null`::
  2817. None == any_(mytable.c.somearray)
  2818. The any_() / all_() operators also feature a special "operand flipping"
  2819. behavior such that if any_() / all_() are used on the left side of a
  2820. comparison using a standalone operator such as ``==``, ``!=``, etc.
  2821. (not including operator methods such as
  2822. :meth:`_sql.ColumnOperators.is_`) the rendered expression is flipped::
  2823. # would render '5 = ANY (column)`
  2824. any_(mytable.c.column) == 5
  2825. Or with ``None``, which note will not perform
  2826. the usual step of rendering "IS" as is normally the case for NULL::
  2827. # would render 'NULL = ANY(somearray)'
  2828. any_(mytable.c.somearray) == None
  2829. .. versionchanged:: 1.4.26 repaired the use of any_() / all_()
  2830. comparing to NULL on the right side to be flipped to the left.
  2831. The column-level :meth:`_sql.ColumnElement.any_` method (not to be
  2832. confused with :class:`_types.ARRAY` level
  2833. :meth:`_types.ARRAY.Comparator.any`) is shorthand for
  2834. ``any_(col)``::
  2835. 5 = mytable.c.somearray.any_()
  2836. .. seealso::
  2837. :meth:`_sql.ColumnOperators.any_`
  2838. :func:`_expression.all_`
  2839. """
  2840. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2841. expr = expr.self_group()
  2842. return CollectionAggregate(
  2843. expr,
  2844. operator=operators.any_op,
  2845. type_=type_api.NULLTYPE,
  2846. wraps_column_expression=False,
  2847. )
  2848. @classmethod
  2849. def _create_all(cls, expr):
  2850. """Produce an ALL expression.
  2851. For dialects such as that of PostgreSQL, this operator applies
  2852. to usage of the :class:`_types.ARRAY` datatype, for that of
  2853. MySQL, it may apply to a subquery. e.g.::
  2854. # renders on PostgreSQL:
  2855. # '5 = ALL (somearray)'
  2856. expr = 5 == all_(mytable.c.somearray)
  2857. # renders on MySQL:
  2858. # '5 = ALL (SELECT value FROM table)'
  2859. expr = 5 == all_(select(table.c.value))
  2860. Comparison to NULL may work using ``None``::
  2861. None == all_(mytable.c.somearray)
  2862. The any_() / all_() operators also feature a special "operand flipping"
  2863. behavior such that if any_() / all_() are used on the left side of a
  2864. comparison using a standalone operator such as ``==``, ``!=``, etc.
  2865. (not including operator methods such as
  2866. :meth:`_sql.ColumnOperators.is_`) the rendered expression is flipped::
  2867. # would render '5 = ALL (column)`
  2868. all_(mytable.c.column) == 5
  2869. Or with ``None``, which note will not perform
  2870. the usual step of rendering "IS" as is normally the case for NULL::
  2871. # would render 'NULL = ALL(somearray)'
  2872. all_(mytable.c.somearray) == None
  2873. .. versionchanged:: 1.4.26 repaired the use of any_() / all_()
  2874. comparing to NULL on the right side to be flipped to the left.
  2875. The column-level :meth:`_sql.ColumnElement.all_` method (not to be
  2876. confused with :class:`_types.ARRAY` level
  2877. :meth:`_types.ARRAY.Comparator.all`) is shorthand for
  2878. ``all_(col)``::
  2879. 5 == mytable.c.somearray.all_()
  2880. .. seealso::
  2881. :meth:`_sql.ColumnOperators.all_`
  2882. :func:`_expression.any_`
  2883. """
  2884. expr = coercions.expect(roles.ExpressionElementRole, expr)
  2885. expr = expr.self_group()
  2886. return CollectionAggregate(
  2887. expr,
  2888. operator=operators.all_op,
  2889. type_=type_api.NULLTYPE,
  2890. wraps_column_expression=False,
  2891. )
  2892. # operate and reverse_operate are hardwired to
  2893. # dispatch onto the type comparator directly, so that we can
  2894. # ensure "reversed" behavior.
  2895. def operate(self, op, *other, **kwargs):
  2896. if not operators.is_comparison(op):
  2897. raise exc.ArgumentError(
  2898. "Only comparison operators may be used with ANY/ALL"
  2899. )
  2900. kwargs["reverse"] = kwargs["_any_all_expr"] = True
  2901. return self.comparator.operate(operators.mirror(op), *other, **kwargs)
  2902. def reverse_operate(self, op, other, **kwargs):
  2903. # comparison operators should never call reverse_operate
  2904. assert not operators.is_comparison(op)
  2905. raise exc.ArgumentError(
  2906. "Only comparison operators may be used with ANY/ALL"
  2907. )
  2908. class AsBoolean(WrapsColumnExpression, UnaryExpression):
  2909. inherit_cache = True
  2910. def __init__(self, element, operator, negate):
  2911. self.element = element
  2912. self.type = type_api.BOOLEANTYPE
  2913. self.operator = operator
  2914. self.negate = negate
  2915. self.modifier = None
  2916. self.wraps_column_expression = True
  2917. self._is_implicitly_boolean = element._is_implicitly_boolean
  2918. @property
  2919. def wrapped_column_expression(self):
  2920. return self.element
  2921. def self_group(self, against=None):
  2922. return self
  2923. def _negate(self):
  2924. if isinstance(self.element, (True_, False_)):
  2925. return self.element._negate()
  2926. else:
  2927. return AsBoolean(self.element, self.negate, self.operator)
  2928. class BinaryExpression(ColumnElement):
  2929. """Represent an expression that is ``LEFT <operator> RIGHT``.
  2930. A :class:`.BinaryExpression` is generated automatically
  2931. whenever two column expressions are used in a Python binary expression::
  2932. >>> from sqlalchemy.sql import column
  2933. >>> column('a') + column('b')
  2934. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  2935. >>> print(column('a') + column('b'))
  2936. a + b
  2937. """
  2938. __visit_name__ = "binary"
  2939. _traverse_internals = [
  2940. ("left", InternalTraversal.dp_clauseelement),
  2941. ("right", InternalTraversal.dp_clauseelement),
  2942. ("operator", InternalTraversal.dp_operator),
  2943. ("negate", InternalTraversal.dp_operator),
  2944. ("modifiers", InternalTraversal.dp_plain_dict),
  2945. (
  2946. "type",
  2947. InternalTraversal.dp_type,
  2948. ), # affects JSON CAST operators
  2949. ]
  2950. _is_implicitly_boolean = True
  2951. """Indicates that any database will know this is a boolean expression
  2952. even if the database does not have an explicit boolean datatype.
  2953. """
  2954. def __init__(
  2955. self, left, right, operator, type_=None, negate=None, modifiers=None
  2956. ):
  2957. # allow compatibility with libraries that
  2958. # refer to BinaryExpression directly and pass strings
  2959. if isinstance(operator, util.string_types):
  2960. operator = operators.custom_op(operator)
  2961. self._orig = (left.__hash__(), right.__hash__())
  2962. self._propagate_attrs = left._propagate_attrs or right._propagate_attrs
  2963. self.left = left.self_group(against=operator)
  2964. self.right = right.self_group(against=operator)
  2965. self.operator = operator
  2966. self.type = type_api.to_instance(type_)
  2967. self.negate = negate
  2968. self._is_implicitly_boolean = operators.is_boolean(operator)
  2969. if modifiers is None:
  2970. self.modifiers = {}
  2971. else:
  2972. self.modifiers = modifiers
  2973. def __bool__(self):
  2974. if self.operator in (operator.eq, operator.ne):
  2975. return self.operator(*self._orig)
  2976. else:
  2977. raise TypeError("Boolean value of this clause is not defined")
  2978. __nonzero__ = __bool__
  2979. @property
  2980. def is_comparison(self):
  2981. return operators.is_comparison(self.operator)
  2982. @property
  2983. def _from_objects(self):
  2984. return self.left._from_objects + self.right._from_objects
  2985. def self_group(self, against=None):
  2986. if operators.is_precedent(self.operator, against):
  2987. return Grouping(self)
  2988. else:
  2989. return self
  2990. def _negate(self):
  2991. if self.negate is not None:
  2992. return BinaryExpression(
  2993. self.left,
  2994. self.right._negate_in_binary(self.negate, self.operator),
  2995. self.negate,
  2996. negate=self.operator,
  2997. type_=self.type,
  2998. modifiers=self.modifiers,
  2999. )
  3000. else:
  3001. return super(BinaryExpression, self)._negate()
  3002. class Slice(ColumnElement):
  3003. """Represent SQL for a Python array-slice object.
  3004. This is not a specific SQL construct at this level, but
  3005. may be interpreted by specific dialects, e.g. PostgreSQL.
  3006. """
  3007. __visit_name__ = "slice"
  3008. _traverse_internals = [
  3009. ("start", InternalTraversal.dp_clauseelement),
  3010. ("stop", InternalTraversal.dp_clauseelement),
  3011. ("step", InternalTraversal.dp_clauseelement),
  3012. ]
  3013. def __init__(self, start, stop, step, _name=None):
  3014. self.start = coercions.expect(
  3015. roles.ExpressionElementRole,
  3016. start,
  3017. name=_name,
  3018. type_=type_api.INTEGERTYPE,
  3019. )
  3020. self.stop = coercions.expect(
  3021. roles.ExpressionElementRole,
  3022. stop,
  3023. name=_name,
  3024. type_=type_api.INTEGERTYPE,
  3025. )
  3026. self.step = coercions.expect(
  3027. roles.ExpressionElementRole,
  3028. step,
  3029. name=_name,
  3030. type_=type_api.INTEGERTYPE,
  3031. )
  3032. self.type = type_api.NULLTYPE
  3033. def self_group(self, against=None):
  3034. assert against is operator.getitem
  3035. return self
  3036. class IndexExpression(BinaryExpression):
  3037. """Represent the class of expressions that are like an "index"
  3038. operation."""
  3039. inherit_cache = True
  3040. class GroupedElement(ClauseElement):
  3041. """Represent any parenthesized expression"""
  3042. __visit_name__ = "grouping"
  3043. def self_group(self, against=None):
  3044. return self
  3045. def _ungroup(self):
  3046. return self.element._ungroup()
  3047. class Grouping(GroupedElement, ColumnElement):
  3048. """Represent a grouping within a column expression"""
  3049. _traverse_internals = [
  3050. ("element", InternalTraversal.dp_clauseelement),
  3051. ("type", InternalTraversal.dp_type),
  3052. ]
  3053. def __init__(self, element):
  3054. self.element = element
  3055. self.type = getattr(element, "type", type_api.NULLTYPE)
  3056. def _with_binary_element_type(self, type_):
  3057. return self.__class__(self.element._with_binary_element_type(type_))
  3058. @util.memoized_property
  3059. def _is_implicitly_boolean(self):
  3060. return self.element._is_implicitly_boolean
  3061. @property
  3062. def _tq_label(self):
  3063. return (
  3064. getattr(self.element, "_tq_label", None) or self._anon_name_label
  3065. )
  3066. @property
  3067. def _proxies(self):
  3068. if isinstance(self.element, ColumnElement):
  3069. return [self.element]
  3070. else:
  3071. return []
  3072. @property
  3073. def _from_objects(self):
  3074. return self.element._from_objects
  3075. def __getattr__(self, attr):
  3076. return getattr(self.element, attr)
  3077. def __getstate__(self):
  3078. return {"element": self.element, "type": self.type}
  3079. def __setstate__(self, state):
  3080. self.element = state["element"]
  3081. self.type = state["type"]
  3082. RANGE_UNBOUNDED = util.symbol("RANGE_UNBOUNDED")
  3083. RANGE_CURRENT = util.symbol("RANGE_CURRENT")
  3084. class Over(ColumnElement):
  3085. """Represent an OVER clause.
  3086. This is a special operator against a so-called
  3087. "window" function, as well as any aggregate function,
  3088. which produces results relative to the result set
  3089. itself. Most modern SQL backends now support window functions.
  3090. """
  3091. __visit_name__ = "over"
  3092. _traverse_internals = [
  3093. ("element", InternalTraversal.dp_clauseelement),
  3094. ("order_by", InternalTraversal.dp_clauseelement),
  3095. ("partition_by", InternalTraversal.dp_clauseelement),
  3096. ("range_", InternalTraversal.dp_plain_obj),
  3097. ("rows", InternalTraversal.dp_plain_obj),
  3098. ]
  3099. order_by = None
  3100. partition_by = None
  3101. element = None
  3102. """The underlying expression object to which this :class:`.Over`
  3103. object refers towards."""
  3104. def __init__(
  3105. self, element, partition_by=None, order_by=None, range_=None, rows=None
  3106. ):
  3107. r"""Produce an :class:`.Over` object against a function.
  3108. Used against aggregate or so-called "window" functions,
  3109. for database backends that support window functions.
  3110. :func:`_expression.over` is usually called using
  3111. the :meth:`.FunctionElement.over` method, e.g.::
  3112. func.row_number().over(order_by=mytable.c.some_column)
  3113. Would produce::
  3114. ROW_NUMBER() OVER(ORDER BY some_column)
  3115. Ranges are also possible using the :paramref:`.expression.over.range_`
  3116. and :paramref:`.expression.over.rows` parameters. These
  3117. mutually-exclusive parameters each accept a 2-tuple, which contains
  3118. a combination of integers and None::
  3119. func.row_number().over(
  3120. order_by=my_table.c.some_column, range_=(None, 0))
  3121. The above would produce::
  3122. ROW_NUMBER() OVER(ORDER BY some_column
  3123. RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
  3124. A value of ``None`` indicates "unbounded", a
  3125. value of zero indicates "current row", and negative / positive
  3126. integers indicate "preceding" and "following":
  3127. * RANGE BETWEEN 5 PRECEDING AND 10 FOLLOWING::
  3128. func.row_number().over(order_by='x', range_=(-5, 10))
  3129. * ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW::
  3130. func.row_number().over(order_by='x', rows=(None, 0))
  3131. * RANGE BETWEEN 2 PRECEDING AND UNBOUNDED FOLLOWING::
  3132. func.row_number().over(order_by='x', range_=(-2, None))
  3133. * RANGE BETWEEN 1 FOLLOWING AND 3 FOLLOWING::
  3134. func.row_number().over(order_by='x', range_=(1, 3))
  3135. .. versionadded:: 1.1 support for RANGE / ROWS within a window
  3136. :param element: a :class:`.FunctionElement`, :class:`.WithinGroup`,
  3137. or other compatible construct.
  3138. :param partition_by: a column element or string, or a list
  3139. of such, that will be used as the PARTITION BY clause
  3140. of the OVER construct.
  3141. :param order_by: a column element or string, or a list
  3142. of such, that will be used as the ORDER BY clause
  3143. of the OVER construct.
  3144. :param range\_: optional range clause for the window. This is a
  3145. tuple value which can contain integer values or ``None``,
  3146. and will render a RANGE BETWEEN PRECEDING / FOLLOWING clause.
  3147. .. versionadded:: 1.1
  3148. :param rows: optional rows clause for the window. This is a tuple
  3149. value which can contain integer values or None, and will render
  3150. a ROWS BETWEEN PRECEDING / FOLLOWING clause.
  3151. .. versionadded:: 1.1
  3152. This function is also available from the :data:`~.expression.func`
  3153. construct itself via the :meth:`.FunctionElement.over` method.
  3154. .. seealso::
  3155. :ref:`tutorial_window_functions` - in the :ref:`unified_tutorial`
  3156. :data:`.expression.func`
  3157. :func:`_expression.within_group`
  3158. """
  3159. self.element = element
  3160. if order_by is not None:
  3161. self.order_by = ClauseList(
  3162. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3163. )
  3164. if partition_by is not None:
  3165. self.partition_by = ClauseList(
  3166. *util.to_list(partition_by),
  3167. _literal_as_text_role=roles.ByOfRole
  3168. )
  3169. if range_:
  3170. self.range_ = self._interpret_range(range_)
  3171. if rows:
  3172. raise exc.ArgumentError(
  3173. "'range_' and 'rows' are mutually exclusive"
  3174. )
  3175. else:
  3176. self.rows = None
  3177. elif rows:
  3178. self.rows = self._interpret_range(rows)
  3179. self.range_ = None
  3180. else:
  3181. self.rows = self.range_ = None
  3182. def __reduce__(self):
  3183. return self.__class__, (
  3184. self.element,
  3185. self.partition_by,
  3186. self.order_by,
  3187. self.range_,
  3188. self.rows,
  3189. )
  3190. def _interpret_range(self, range_):
  3191. if not isinstance(range_, tuple) or len(range_) != 2:
  3192. raise exc.ArgumentError("2-tuple expected for range/rows")
  3193. if range_[0] is None:
  3194. lower = RANGE_UNBOUNDED
  3195. else:
  3196. try:
  3197. lower = int(range_[0])
  3198. except ValueError as err:
  3199. util.raise_(
  3200. exc.ArgumentError(
  3201. "Integer or None expected for range value"
  3202. ),
  3203. replace_context=err,
  3204. )
  3205. else:
  3206. if lower == 0:
  3207. lower = RANGE_CURRENT
  3208. if range_[1] is None:
  3209. upper = RANGE_UNBOUNDED
  3210. else:
  3211. try:
  3212. upper = int(range_[1])
  3213. except ValueError as err:
  3214. util.raise_(
  3215. exc.ArgumentError(
  3216. "Integer or None expected for range value"
  3217. ),
  3218. replace_context=err,
  3219. )
  3220. else:
  3221. if upper == 0:
  3222. upper = RANGE_CURRENT
  3223. return lower, upper
  3224. @util.memoized_property
  3225. def type(self):
  3226. return self.element.type
  3227. @property
  3228. def _from_objects(self):
  3229. return list(
  3230. itertools.chain(
  3231. *[
  3232. c._from_objects
  3233. for c in (self.element, self.partition_by, self.order_by)
  3234. if c is not None
  3235. ]
  3236. )
  3237. )
  3238. class WithinGroup(ColumnElement):
  3239. """Represent a WITHIN GROUP (ORDER BY) clause.
  3240. This is a special operator against so-called
  3241. "ordered set aggregate" and "hypothetical
  3242. set aggregate" functions, including ``percentile_cont()``,
  3243. ``rank()``, ``dense_rank()``, etc.
  3244. It's supported only by certain database backends, such as PostgreSQL,
  3245. Oracle and MS SQL Server.
  3246. The :class:`.WithinGroup` construct extracts its type from the
  3247. method :meth:`.FunctionElement.within_group_type`. If this returns
  3248. ``None``, the function's ``.type`` is used.
  3249. """
  3250. __visit_name__ = "withingroup"
  3251. _traverse_internals = [
  3252. ("element", InternalTraversal.dp_clauseelement),
  3253. ("order_by", InternalTraversal.dp_clauseelement),
  3254. ]
  3255. order_by = None
  3256. def __init__(self, element, *order_by):
  3257. r"""Produce a :class:`.WithinGroup` object against a function.
  3258. Used against so-called "ordered set aggregate" and "hypothetical
  3259. set aggregate" functions, including :class:`.percentile_cont`,
  3260. :class:`.rank`, :class:`.dense_rank`, etc.
  3261. :func:`_expression.within_group` is usually called using
  3262. the :meth:`.FunctionElement.within_group` method, e.g.::
  3263. from sqlalchemy import within_group
  3264. stmt = select(
  3265. department.c.id,
  3266. func.percentile_cont(0.5).within_group(
  3267. department.c.salary.desc()
  3268. )
  3269. )
  3270. The above statement would produce SQL similar to
  3271. ``SELECT department.id, percentile_cont(0.5)
  3272. WITHIN GROUP (ORDER BY department.salary DESC)``.
  3273. :param element: a :class:`.FunctionElement` construct, typically
  3274. generated by :data:`~.expression.func`.
  3275. :param \*order_by: one or more column elements that will be used
  3276. as the ORDER BY clause of the WITHIN GROUP construct.
  3277. .. versionadded:: 1.1
  3278. .. seealso::
  3279. :ref:`tutorial_functions_within_group` - in the
  3280. :ref:`unified_tutorial`
  3281. :data:`.expression.func`
  3282. :func:`_expression.over`
  3283. """
  3284. self.element = element
  3285. if order_by is not None:
  3286. self.order_by = ClauseList(
  3287. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3288. )
  3289. def __reduce__(self):
  3290. return self.__class__, (self.element,) + tuple(self.order_by)
  3291. def over(self, partition_by=None, order_by=None, range_=None, rows=None):
  3292. """Produce an OVER clause against this :class:`.WithinGroup`
  3293. construct.
  3294. This function has the same signature as that of
  3295. :meth:`.FunctionElement.over`.
  3296. """
  3297. return Over(
  3298. self,
  3299. partition_by=partition_by,
  3300. order_by=order_by,
  3301. range_=range_,
  3302. rows=rows,
  3303. )
  3304. @util.memoized_property
  3305. def type(self):
  3306. wgt = self.element.within_group_type(self)
  3307. if wgt is not None:
  3308. return wgt
  3309. else:
  3310. return self.element.type
  3311. @property
  3312. def _from_objects(self):
  3313. return list(
  3314. itertools.chain(
  3315. *[
  3316. c._from_objects
  3317. for c in (self.element, self.order_by)
  3318. if c is not None
  3319. ]
  3320. )
  3321. )
  3322. class FunctionFilter(ColumnElement):
  3323. """Represent a function FILTER clause.
  3324. This is a special operator against aggregate and window functions,
  3325. which controls which rows are passed to it.
  3326. It's supported only by certain database backends.
  3327. Invocation of :class:`.FunctionFilter` is via
  3328. :meth:`.FunctionElement.filter`::
  3329. func.count(1).filter(True)
  3330. .. versionadded:: 1.0.0
  3331. .. seealso::
  3332. :meth:`.FunctionElement.filter`
  3333. """
  3334. __visit_name__ = "funcfilter"
  3335. _traverse_internals = [
  3336. ("func", InternalTraversal.dp_clauseelement),
  3337. ("criterion", InternalTraversal.dp_clauseelement),
  3338. ]
  3339. criterion = None
  3340. def __init__(self, func, *criterion):
  3341. """Produce a :class:`.FunctionFilter` object against a function.
  3342. Used against aggregate and window functions,
  3343. for database backends that support the "FILTER" clause.
  3344. E.g.::
  3345. from sqlalchemy import funcfilter
  3346. funcfilter(func.count(1), MyClass.name == 'some name')
  3347. Would produce "COUNT(1) FILTER (WHERE myclass.name = 'some name')".
  3348. This function is also available from the :data:`~.expression.func`
  3349. construct itself via the :meth:`.FunctionElement.filter` method.
  3350. .. versionadded:: 1.0.0
  3351. .. seealso::
  3352. :ref:`tutorial_functions_within_group` - in the
  3353. :ref:`unified_tutorial`
  3354. :meth:`.FunctionElement.filter`
  3355. """
  3356. self.func = func
  3357. self.filter(*criterion)
  3358. def filter(self, *criterion):
  3359. """Produce an additional FILTER against the function.
  3360. This method adds additional criteria to the initial criteria
  3361. set up by :meth:`.FunctionElement.filter`.
  3362. Multiple criteria are joined together at SQL render time
  3363. via ``AND``.
  3364. """
  3365. for criterion in list(criterion):
  3366. criterion = coercions.expect(roles.WhereHavingRole, criterion)
  3367. if self.criterion is not None:
  3368. self.criterion = self.criterion & criterion
  3369. else:
  3370. self.criterion = criterion
  3371. return self
  3372. def over(self, partition_by=None, order_by=None, range_=None, rows=None):
  3373. """Produce an OVER clause against this filtered function.
  3374. Used against aggregate or so-called "window" functions,
  3375. for database backends that support window functions.
  3376. The expression::
  3377. func.rank().filter(MyClass.y > 5).over(order_by='x')
  3378. is shorthand for::
  3379. from sqlalchemy import over, funcfilter
  3380. over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')
  3381. See :func:`_expression.over` for a full description.
  3382. """
  3383. return Over(
  3384. self,
  3385. partition_by=partition_by,
  3386. order_by=order_by,
  3387. range_=range_,
  3388. rows=rows,
  3389. )
  3390. def self_group(self, against=None):
  3391. if operators.is_precedent(operators.filter_op, against):
  3392. return Grouping(self)
  3393. else:
  3394. return self
  3395. @util.memoized_property
  3396. def type(self):
  3397. return self.func.type
  3398. @property
  3399. def _from_objects(self):
  3400. return list(
  3401. itertools.chain(
  3402. *[
  3403. c._from_objects
  3404. for c in (self.func, self.criterion)
  3405. if c is not None
  3406. ]
  3407. )
  3408. )
  3409. class Label(roles.LabeledColumnExprRole, ColumnElement):
  3410. """Represents a column label (AS).
  3411. Represent a label, as typically applied to any column-level
  3412. element using the ``AS`` sql keyword.
  3413. """
  3414. __visit_name__ = "label"
  3415. _traverse_internals = [
  3416. ("name", InternalTraversal.dp_anon_name),
  3417. ("_type", InternalTraversal.dp_type),
  3418. ("_element", InternalTraversal.dp_clauseelement),
  3419. ]
  3420. def __init__(self, name, element, type_=None):
  3421. """Return a :class:`Label` object for the
  3422. given :class:`_expression.ColumnElement`.
  3423. A label changes the name of an element in the columns clause of a
  3424. ``SELECT`` statement, typically via the ``AS`` SQL keyword.
  3425. This functionality is more conveniently available via the
  3426. :meth:`_expression.ColumnElement.label` method on
  3427. :class:`_expression.ColumnElement`.
  3428. :param name: label name
  3429. :param obj: a :class:`_expression.ColumnElement`.
  3430. """
  3431. orig_element = element
  3432. element = coercions.expect(
  3433. roles.ExpressionElementRole,
  3434. element,
  3435. apply_propagate_attrs=self,
  3436. )
  3437. while isinstance(element, Label):
  3438. # TODO: this is only covered in test_text.py, but nothing
  3439. # fails if it's removed. determine rationale
  3440. element = element.element
  3441. if name:
  3442. self.name = name
  3443. else:
  3444. self.name = _anonymous_label.safe_construct(
  3445. id(self), getattr(element, "name", "anon")
  3446. )
  3447. if isinstance(orig_element, Label):
  3448. # TODO: no coverage for this block, again would be in
  3449. # test_text.py where the resolve_label concept is important
  3450. self._resolve_label = orig_element._label
  3451. self.key = self._tq_label = self._tq_key_label = self.name
  3452. self._element = element
  3453. self._type = type_
  3454. self._proxies = [element]
  3455. def __reduce__(self):
  3456. return self.__class__, (self.name, self._element, self._type)
  3457. @util.memoized_property
  3458. def _is_implicitly_boolean(self):
  3459. return self.element._is_implicitly_boolean
  3460. @HasMemoized.memoized_attribute
  3461. def _allow_label_resolve(self):
  3462. return self.element._allow_label_resolve
  3463. @property
  3464. def _order_by_label_element(self):
  3465. return self
  3466. @util.memoized_property
  3467. def type(self):
  3468. return type_api.to_instance(
  3469. self._type or getattr(self._element, "type", None)
  3470. )
  3471. @HasMemoized.memoized_attribute
  3472. def element(self):
  3473. return self._element.self_group(against=operators.as_)
  3474. def self_group(self, against=None):
  3475. return self._apply_to_inner(self._element.self_group, against=against)
  3476. def _negate(self):
  3477. return self._apply_to_inner(self._element._negate)
  3478. def _apply_to_inner(self, fn, *arg, **kw):
  3479. sub_element = fn(*arg, **kw)
  3480. if sub_element is not self._element:
  3481. return Label(self.name, sub_element, type_=self._type)
  3482. else:
  3483. return self
  3484. @property
  3485. def primary_key(self):
  3486. return self.element.primary_key
  3487. @property
  3488. def foreign_keys(self):
  3489. return self.element.foreign_keys
  3490. def _copy_internals(self, clone=_clone, anonymize_labels=False, **kw):
  3491. self._reset_memoizations()
  3492. self._element = clone(self._element, **kw)
  3493. if anonymize_labels:
  3494. self.name = _anonymous_label.safe_construct(
  3495. id(self), getattr(self.element, "name", "anon")
  3496. )
  3497. self.key = self._tq_label = self._tq_key_label = self.name
  3498. @property
  3499. def _from_objects(self):
  3500. return self.element._from_objects
  3501. def _make_proxy(self, selectable, name=None, **kw):
  3502. name = self.name if not name else name
  3503. key, e = self.element._make_proxy(
  3504. selectable,
  3505. name=name,
  3506. disallow_is_literal=True,
  3507. name_is_truncatable=isinstance(name, _truncated_label),
  3508. )
  3509. # there was a note here to remove this assertion, which was here
  3510. # to determine if we later could support a use case where
  3511. # the key and name of a label are separate. But I don't know what
  3512. # that case was. For now, this is an unexpected case that occurs
  3513. # when a label name conflicts with other columns and select()
  3514. # is attempting to disambiguate an explicit label, which is not what
  3515. # the user would want. See issue #6090.
  3516. if key != self.name:
  3517. raise exc.InvalidRequestError(
  3518. "Label name %s is being renamed to an anonymous label due "
  3519. "to disambiguation "
  3520. "which is not supported right now. Please use unique names "
  3521. "for explicit labels." % (self.name)
  3522. )
  3523. e._propagate_attrs = selectable._propagate_attrs
  3524. e._proxies.append(self)
  3525. if self._type is not None:
  3526. e.type = self._type
  3527. return self.key, e
  3528. class NamedColumn(ColumnElement):
  3529. is_literal = False
  3530. table = None
  3531. def _compare_name_for_result(self, other):
  3532. return (hasattr(other, "name") and self.name == other.name) or (
  3533. hasattr(other, "_label") and self._label == other._label
  3534. )
  3535. @util.memoized_property
  3536. def description(self):
  3537. if util.py3k:
  3538. return self.name
  3539. else:
  3540. return self.name.encode("ascii", "backslashreplace")
  3541. @HasMemoized.memoized_attribute
  3542. def _tq_key_label(self):
  3543. """table qualified label based on column key.
  3544. for table-bound columns this is <tablename>_<column key/proxy key>;
  3545. all other expressions it resolves to key/proxy key.
  3546. """
  3547. proxy_key = self._proxy_key
  3548. if proxy_key and proxy_key != self.name:
  3549. return self._gen_tq_label(proxy_key)
  3550. else:
  3551. return self._tq_label
  3552. @HasMemoized.memoized_attribute
  3553. def _tq_label(self):
  3554. """table qualified label based on column name.
  3555. for table-bound columns this is <tablename>_<columnname>; all other
  3556. expressions it resolves to .name.
  3557. """
  3558. return self._gen_tq_label(self.name)
  3559. @HasMemoized.memoized_attribute
  3560. def _render_label_in_columns_clause(self):
  3561. return True
  3562. @HasMemoized.memoized_attribute
  3563. def _non_anon_label(self):
  3564. return self.name
  3565. def _gen_tq_label(self, name, dedupe_on_key=True):
  3566. return name
  3567. def _bind_param(self, operator, obj, type_=None, expanding=False):
  3568. return BindParameter(
  3569. self.key,
  3570. obj,
  3571. _compared_to_operator=operator,
  3572. _compared_to_type=self.type,
  3573. type_=type_,
  3574. unique=True,
  3575. expanding=expanding,
  3576. )
  3577. def _make_proxy(
  3578. self,
  3579. selectable,
  3580. name=None,
  3581. name_is_truncatable=False,
  3582. disallow_is_literal=False,
  3583. **kw
  3584. ):
  3585. c = ColumnClause(
  3586. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3587. if name_is_truncatable
  3588. else (name or self.name),
  3589. type_=self.type,
  3590. _selectable=selectable,
  3591. is_literal=False,
  3592. )
  3593. c._propagate_attrs = selectable._propagate_attrs
  3594. if name is None:
  3595. c.key = self.key
  3596. c._proxies = [self]
  3597. if selectable._is_clone_of is not None:
  3598. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  3599. return c.key, c
  3600. class ColumnClause(
  3601. roles.DDLReferredColumnRole,
  3602. roles.LabeledColumnExprRole,
  3603. roles.StrAsPlainColumnRole,
  3604. Immutable,
  3605. NamedColumn,
  3606. ):
  3607. """Represents a column expression from any textual string.
  3608. The :class:`.ColumnClause`, a lightweight analogue to the
  3609. :class:`_schema.Column` class, is typically invoked using the
  3610. :func:`_expression.column` function, as in::
  3611. from sqlalchemy import column
  3612. id, name = column("id"), column("name")
  3613. stmt = select(id, name).select_from("user")
  3614. The above statement would produce SQL like::
  3615. SELECT id, name FROM user
  3616. :class:`.ColumnClause` is the immediate superclass of the schema-specific
  3617. :class:`_schema.Column` object. While the :class:`_schema.Column`
  3618. class has all the
  3619. same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause`
  3620. class is usable by itself in those cases where behavioral requirements
  3621. are limited to simple SQL expression generation. The object has none of
  3622. the associations with schema-level metadata or with execution-time
  3623. behavior that :class:`_schema.Column` does,
  3624. so in that sense is a "lightweight"
  3625. version of :class:`_schema.Column`.
  3626. Full details on :class:`.ColumnClause` usage is at
  3627. :func:`_expression.column`.
  3628. .. seealso::
  3629. :func:`_expression.column`
  3630. :class:`_schema.Column`
  3631. """
  3632. table = None
  3633. is_literal = False
  3634. __visit_name__ = "column"
  3635. _traverse_internals = [
  3636. ("name", InternalTraversal.dp_anon_name),
  3637. ("type", InternalTraversal.dp_type),
  3638. ("table", InternalTraversal.dp_clauseelement),
  3639. ("is_literal", InternalTraversal.dp_boolean),
  3640. ]
  3641. onupdate = default = server_default = server_onupdate = None
  3642. _is_multiparam_column = False
  3643. def __init__(self, text, type_=None, is_literal=False, _selectable=None):
  3644. """Produce a :class:`.ColumnClause` object.
  3645. The :class:`.ColumnClause` is a lightweight analogue to the
  3646. :class:`_schema.Column` class. The :func:`_expression.column`
  3647. function can
  3648. be invoked with just a name alone, as in::
  3649. from sqlalchemy import column
  3650. id, name = column("id"), column("name")
  3651. stmt = select(id, name).select_from("user")
  3652. The above statement would produce SQL like::
  3653. SELECT id, name FROM user
  3654. Once constructed, :func:`_expression.column`
  3655. may be used like any other SQL
  3656. expression element such as within :func:`_expression.select`
  3657. constructs::
  3658. from sqlalchemy.sql import column
  3659. id, name = column("id"), column("name")
  3660. stmt = select(id, name).select_from("user")
  3661. The text handled by :func:`_expression.column`
  3662. is assumed to be handled
  3663. like the name of a database column; if the string contains mixed case,
  3664. special characters, or matches a known reserved word on the target
  3665. backend, the column expression will render using the quoting
  3666. behavior determined by the backend. To produce a textual SQL
  3667. expression that is rendered exactly without any quoting,
  3668. use :func:`_expression.literal_column` instead,
  3669. or pass ``True`` as the
  3670. value of :paramref:`_expression.column.is_literal`. Additionally,
  3671. full SQL
  3672. statements are best handled using the :func:`_expression.text`
  3673. construct.
  3674. :func:`_expression.column` can be used in a table-like
  3675. fashion by combining it with the :func:`.table` function
  3676. (which is the lightweight analogue to :class:`_schema.Table`
  3677. ) to produce
  3678. a working table construct with minimal boilerplate::
  3679. from sqlalchemy import table, column, select
  3680. user = table("user",
  3681. column("id"),
  3682. column("name"),
  3683. column("description"),
  3684. )
  3685. stmt = select(user.c.description).where(user.c.name == 'wendy')
  3686. A :func:`_expression.column` / :func:`.table`
  3687. construct like that illustrated
  3688. above can be created in an
  3689. ad-hoc fashion and is not associated with any
  3690. :class:`_schema.MetaData`, DDL, or events, unlike its
  3691. :class:`_schema.Table` counterpart.
  3692. .. versionchanged:: 1.0.0 :func:`_expression.column` can now
  3693. be imported from the plain ``sqlalchemy`` namespace like any
  3694. other SQL element.
  3695. :param text: the text of the element.
  3696. :param type: :class:`_types.TypeEngine` object which can associate
  3697. this :class:`.ColumnClause` with a type.
  3698. :param is_literal: if True, the :class:`.ColumnClause` is assumed to
  3699. be an exact expression that will be delivered to the output with no
  3700. quoting rules applied regardless of case sensitive settings. the
  3701. :func:`_expression.literal_column()` function essentially invokes
  3702. :func:`_expression.column` while passing ``is_literal=True``.
  3703. .. seealso::
  3704. :class:`_schema.Column`
  3705. :func:`_expression.literal_column`
  3706. :func:`.table`
  3707. :func:`_expression.text`
  3708. :ref:`sqlexpression_literal_column`
  3709. """
  3710. self.key = self.name = text
  3711. self.table = _selectable
  3712. self.type = type_api.to_instance(type_)
  3713. self.is_literal = is_literal
  3714. def get_children(self, column_tables=False, **kw):
  3715. # override base get_children() to not return the Table
  3716. # or selectable that is parent to this column. Traversals
  3717. # expect the columns of tables and subqueries to be leaf nodes.
  3718. return []
  3719. @property
  3720. def entity_namespace(self):
  3721. if self.table is not None:
  3722. return self.table.entity_namespace
  3723. else:
  3724. return super(ColumnClause, self).entity_namespace
  3725. def _clone(self, detect_subquery_cols=False, **kw):
  3726. if (
  3727. detect_subquery_cols
  3728. and self.table is not None
  3729. and self.table._is_subquery
  3730. ):
  3731. clone = kw.pop("clone")
  3732. table = clone(self.table, **kw)
  3733. new = table.c.corresponding_column(self)
  3734. return new
  3735. return super(ColumnClause, self)._clone(**kw)
  3736. @HasMemoized.memoized_attribute
  3737. def _from_objects(self):
  3738. t = self.table
  3739. if t is not None:
  3740. return [t]
  3741. else:
  3742. return []
  3743. @HasMemoized.memoized_attribute
  3744. def _render_label_in_columns_clause(self):
  3745. return self.table is not None
  3746. @property
  3747. def _ddl_label(self):
  3748. return self._gen_tq_label(self.name, dedupe_on_key=False)
  3749. def _compare_name_for_result(self, other):
  3750. if (
  3751. self.is_literal
  3752. or self.table is None
  3753. or self.table._is_textual
  3754. or not hasattr(other, "proxy_set")
  3755. or (
  3756. isinstance(other, ColumnClause)
  3757. and (
  3758. other.is_literal
  3759. or other.table is None
  3760. or other.table._is_textual
  3761. )
  3762. )
  3763. ):
  3764. return (hasattr(other, "name") and self.name == other.name) or (
  3765. hasattr(other, "_tq_label")
  3766. and self._tq_label == other._tq_label
  3767. )
  3768. else:
  3769. return other.proxy_set.intersection(self.proxy_set)
  3770. def _gen_tq_label(self, name, dedupe_on_key=True):
  3771. """generate table-qualified label
  3772. for a table-bound column this is <tablename>_<columnname>.
  3773. used primarily for LABEL_STYLE_TABLENAME_PLUS_COL
  3774. as well as the .columns collection on a Join object.
  3775. """
  3776. t = self.table
  3777. if self.is_literal:
  3778. return None
  3779. elif t is not None and t.named_with_column:
  3780. if getattr(t, "schema", None):
  3781. label = t.schema.replace(".", "_") + "_" + t.name + "_" + name
  3782. else:
  3783. label = t.name + "_" + name
  3784. # propagate name quoting rules for labels.
  3785. if getattr(name, "quote", None) is not None:
  3786. if isinstance(label, quoted_name):
  3787. label.quote = name.quote
  3788. else:
  3789. label = quoted_name(label, name.quote)
  3790. elif getattr(t.name, "quote", None) is not None:
  3791. # can't get this situation to occur, so let's
  3792. # assert false on it for now
  3793. assert not isinstance(label, quoted_name)
  3794. label = quoted_name(label, t.name.quote)
  3795. if dedupe_on_key:
  3796. # ensure the label name doesn't conflict with that of an
  3797. # existing column. note that this implies that any Column
  3798. # must **not** set up its _label before its parent table has
  3799. # all of its other Column objects set up. There are several
  3800. # tables in the test suite which will fail otherwise; example:
  3801. # table "owner" has columns "name" and "owner_name". Therefore
  3802. # column owner.name cannot use the label "owner_name", it has
  3803. # to be "owner_name_1".
  3804. if label in t.c:
  3805. _label = label
  3806. counter = 1
  3807. while _label in t.c:
  3808. _label = label + "_" + str(counter)
  3809. counter += 1
  3810. label = _label
  3811. return coercions.expect(roles.TruncatedLabelRole, label)
  3812. else:
  3813. return name
  3814. def _make_proxy(
  3815. self,
  3816. selectable,
  3817. name=None,
  3818. name_is_truncatable=False,
  3819. disallow_is_literal=False,
  3820. **kw
  3821. ):
  3822. # the "is_literal" flag normally should never be propagated; a proxied
  3823. # column is always a SQL identifier and never the actual expression
  3824. # being evaluated. however, there is a case where the "is_literal" flag
  3825. # might be used to allow the given identifier to have a fixed quoting
  3826. # pattern already, so maintain the flag for the proxy unless a
  3827. # :class:`.Label` object is creating the proxy. See [ticket:4730].
  3828. is_literal = (
  3829. not disallow_is_literal
  3830. and self.is_literal
  3831. and (
  3832. # note this does not accommodate for quoted_name differences
  3833. # right now
  3834. name is None
  3835. or name == self.name
  3836. )
  3837. )
  3838. c = self._constructor(
  3839. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3840. if name_is_truncatable
  3841. else (name or self.name),
  3842. type_=self.type,
  3843. _selectable=selectable,
  3844. is_literal=is_literal,
  3845. )
  3846. c._propagate_attrs = selectable._propagate_attrs
  3847. if name is None:
  3848. c.key = self.key
  3849. c._proxies = [self]
  3850. if selectable._is_clone_of is not None:
  3851. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  3852. return c.key, c
  3853. class TableValuedColumn(NamedColumn):
  3854. __visit_name__ = "table_valued_column"
  3855. _traverse_internals = [
  3856. ("name", InternalTraversal.dp_anon_name),
  3857. ("type", InternalTraversal.dp_type),
  3858. ("scalar_alias", InternalTraversal.dp_clauseelement),
  3859. ]
  3860. def __init__(self, scalar_alias, type_):
  3861. self.scalar_alias = scalar_alias
  3862. self.key = self.name = scalar_alias.name
  3863. self.type = type_
  3864. def _copy_internals(self, clone=_clone, **kw):
  3865. self.scalar_alias = clone(self.scalar_alias, **kw)
  3866. self.key = self.name = self.scalar_alias.name
  3867. @property
  3868. def _from_objects(self):
  3869. return [self.scalar_alias]
  3870. class CollationClause(ColumnElement):
  3871. __visit_name__ = "collation"
  3872. _traverse_internals = [("collation", InternalTraversal.dp_string)]
  3873. def __init__(self, collation):
  3874. self.collation = collation
  3875. class _IdentifiedClause(Executable, ClauseElement):
  3876. __visit_name__ = "identified"
  3877. _execution_options = Executable._execution_options.union(
  3878. {"autocommit": False}
  3879. )
  3880. def __init__(self, ident):
  3881. self.ident = ident
  3882. class SavepointClause(_IdentifiedClause):
  3883. __visit_name__ = "savepoint"
  3884. inherit_cache = False
  3885. class RollbackToSavepointClause(_IdentifiedClause):
  3886. __visit_name__ = "rollback_to_savepoint"
  3887. inherit_cache = False
  3888. class ReleaseSavepointClause(_IdentifiedClause):
  3889. __visit_name__ = "release_savepoint"
  3890. inherit_cache = False
  3891. class quoted_name(util.MemoizedSlots, util.text_type):
  3892. """Represent a SQL identifier combined with quoting preferences.
  3893. :class:`.quoted_name` is a Python unicode/str subclass which
  3894. represents a particular identifier name along with a
  3895. ``quote`` flag. This ``quote`` flag, when set to
  3896. ``True`` or ``False``, overrides automatic quoting behavior
  3897. for this identifier in order to either unconditionally quote
  3898. or to not quote the name. If left at its default of ``None``,
  3899. quoting behavior is applied to the identifier on a per-backend basis
  3900. based on an examination of the token itself.
  3901. A :class:`.quoted_name` object with ``quote=True`` is also
  3902. prevented from being modified in the case of a so-called
  3903. "name normalize" option. Certain database backends, such as
  3904. Oracle, Firebird, and DB2 "normalize" case-insensitive names
  3905. as uppercase. The SQLAlchemy dialects for these backends
  3906. convert from SQLAlchemy's lower-case-means-insensitive convention
  3907. to the upper-case-means-insensitive conventions of those backends.
  3908. The ``quote=True`` flag here will prevent this conversion from occurring
  3909. to support an identifier that's quoted as all lower case against
  3910. such a backend.
  3911. The :class:`.quoted_name` object is normally created automatically
  3912. when specifying the name for key schema constructs such as
  3913. :class:`_schema.Table`, :class:`_schema.Column`, and others.
  3914. The class can also be
  3915. passed explicitly as the name to any function that receives a name which
  3916. can be quoted. Such as to use the :meth:`_engine.Engine.has_table`
  3917. method with
  3918. an unconditionally quoted name::
  3919. from sqlalchemy import create_engine
  3920. from sqlalchemy.sql import quoted_name
  3921. engine = create_engine("oracle+cx_oracle://some_dsn")
  3922. engine.has_table(quoted_name("some_table", True))
  3923. The above logic will run the "has table" logic against the Oracle backend,
  3924. passing the name exactly as ``"some_table"`` without converting to
  3925. upper case.
  3926. .. versionadded:: 0.9.0
  3927. .. versionchanged:: 1.2 The :class:`.quoted_name` construct is now
  3928. importable from ``sqlalchemy.sql``, in addition to the previous
  3929. location of ``sqlalchemy.sql.elements``.
  3930. """
  3931. __slots__ = "quote", "lower", "upper"
  3932. def __new__(cls, value, quote):
  3933. if value is None:
  3934. return None
  3935. # experimental - don't bother with quoted_name
  3936. # if quote flag is None. doesn't seem to make any dent
  3937. # in performance however
  3938. # elif not sprcls and quote is None:
  3939. # return value
  3940. elif isinstance(value, cls) and (
  3941. quote is None or value.quote == quote
  3942. ):
  3943. return value
  3944. self = super(quoted_name, cls).__new__(cls, value)
  3945. self.quote = quote
  3946. return self
  3947. def __reduce__(self):
  3948. return quoted_name, (util.text_type(self), self.quote)
  3949. def _memoized_method_lower(self):
  3950. if self.quote:
  3951. return self
  3952. else:
  3953. return util.text_type(self).lower()
  3954. def _memoized_method_upper(self):
  3955. if self.quote:
  3956. return self
  3957. else:
  3958. return util.text_type(self).upper()
  3959. def __repr__(self):
  3960. if util.py2k:
  3961. backslashed = self.encode("ascii", "backslashreplace")
  3962. if not util.py2k:
  3963. backslashed = backslashed.decode("ascii")
  3964. return "'%s'" % backslashed
  3965. else:
  3966. return str.__repr__(self)
  3967. def _find_columns(clause):
  3968. """locate Column objects within the given expression."""
  3969. cols = util.column_set()
  3970. traverse(clause, {}, {"column": cols.add})
  3971. return cols
  3972. def _type_from_args(args):
  3973. for a in args:
  3974. if not a.type._isnull:
  3975. return a.type
  3976. else:
  3977. return type_api.NULLTYPE
  3978. def _corresponding_column_or_error(fromclause, column, require_embedded=False):
  3979. c = fromclause.corresponding_column(
  3980. column, require_embedded=require_embedded
  3981. )
  3982. if c is None:
  3983. raise exc.InvalidRequestError(
  3984. "Given column '%s', attached to table '%s', "
  3985. "failed to locate a corresponding column from table '%s'"
  3986. % (column, getattr(column, "table", None), fromclause.description)
  3987. )
  3988. return c
  3989. class AnnotatedColumnElement(Annotated):
  3990. def __init__(self, element, values):
  3991. Annotated.__init__(self, element, values)
  3992. for attr in (
  3993. "comparator",
  3994. "_proxy_key",
  3995. "_tq_key_label",
  3996. "_tq_label",
  3997. "_non_anon_label",
  3998. ):
  3999. self.__dict__.pop(attr, None)
  4000. for attr in ("name", "key", "table"):
  4001. if self.__dict__.get(attr, False) is None:
  4002. self.__dict__.pop(attr)
  4003. def _with_annotations(self, values):
  4004. clone = super(AnnotatedColumnElement, self)._with_annotations(values)
  4005. clone.__dict__.pop("comparator", None)
  4006. return clone
  4007. @util.memoized_property
  4008. def name(self):
  4009. """pull 'name' from parent, if not present"""
  4010. return self._Annotated__element.name
  4011. @util.memoized_property
  4012. def table(self):
  4013. """pull 'table' from parent, if not present"""
  4014. return self._Annotated__element.table
  4015. @util.memoized_property
  4016. def key(self):
  4017. """pull 'key' from parent, if not present"""
  4018. return self._Annotated__element.key
  4019. @util.memoized_property
  4020. def info(self):
  4021. return self._Annotated__element.info
  4022. @util.memoized_property
  4023. def _anon_name_label(self):
  4024. return self._Annotated__element._anon_name_label
  4025. class _truncated_label(quoted_name):
  4026. """A unicode subclass used to identify symbolic "
  4027. "names that may require truncation."""
  4028. __slots__ = ()
  4029. def __new__(cls, value, quote=None):
  4030. quote = getattr(value, "quote", quote)
  4031. # return super(_truncated_label, cls).__new__(cls, value, quote, True)
  4032. return super(_truncated_label, cls).__new__(cls, value, quote)
  4033. def __reduce__(self):
  4034. return self.__class__, (util.text_type(self), self.quote)
  4035. def apply_map(self, map_):
  4036. return self
  4037. class conv(_truncated_label):
  4038. """Mark a string indicating that a name has already been converted
  4039. by a naming convention.
  4040. This is a string subclass that indicates a name that should not be
  4041. subject to any further naming conventions.
  4042. E.g. when we create a :class:`.Constraint` using a naming convention
  4043. as follows::
  4044. m = MetaData(naming_convention={
  4045. "ck": "ck_%(table_name)s_%(constraint_name)s"
  4046. })
  4047. t = Table('t', m, Column('x', Integer),
  4048. CheckConstraint('x > 5', name='x5'))
  4049. The name of the above constraint will be rendered as ``"ck_t_x5"``.
  4050. That is, the existing name ``x5`` is used in the naming convention as the
  4051. ``constraint_name`` token.
  4052. In some situations, such as in migration scripts, we may be rendering
  4053. the above :class:`.CheckConstraint` with a name that's already been
  4054. converted. In order to make sure the name isn't double-modified, the
  4055. new name is applied using the :func:`_schema.conv` marker. We can
  4056. use this explicitly as follows::
  4057. m = MetaData(naming_convention={
  4058. "ck": "ck_%(table_name)s_%(constraint_name)s"
  4059. })
  4060. t = Table('t', m, Column('x', Integer),
  4061. CheckConstraint('x > 5', name=conv('ck_t_x5')))
  4062. Where above, the :func:`_schema.conv` marker indicates that the constraint
  4063. name here is final, and the name will render as ``"ck_t_x5"`` and not
  4064. ``"ck_t_ck_t_x5"``
  4065. .. versionadded:: 0.9.4
  4066. .. seealso::
  4067. :ref:`constraint_naming_conventions`
  4068. """
  4069. __slots__ = ()
  4070. _NONE_NAME = util.symbol("NONE_NAME")
  4071. """indicate a 'deferred' name that was ultimately the value None."""
  4072. # for backwards compatibility in case
  4073. # someone is re-implementing the
  4074. # _truncated_identifier() sequence in a custom
  4075. # compiler
  4076. _generated_label = _truncated_label
  4077. class _anonymous_label(_truncated_label):
  4078. """A unicode subclass used to identify anonymously
  4079. generated names."""
  4080. __slots__ = ()
  4081. @classmethod
  4082. def safe_construct(
  4083. cls, seed, body, enclosing_label=None, sanitize_key=False
  4084. ):
  4085. if sanitize_key:
  4086. body = re.sub(r"[%\(\) \$]+", "_", body).strip("_")
  4087. label = "%%(%d %s)s" % (seed, body.replace("%", "%%"))
  4088. if enclosing_label:
  4089. label = "%s%s" % (enclosing_label, label)
  4090. return _anonymous_label(label)
  4091. def __add__(self, other):
  4092. if "%" in other and not isinstance(other, _anonymous_label):
  4093. other = util.text_type(other).replace("%", "%%")
  4094. else:
  4095. other = util.text_type(other)
  4096. return _anonymous_label(
  4097. quoted_name(
  4098. util.text_type.__add__(self, other),
  4099. self.quote,
  4100. )
  4101. )
  4102. def __radd__(self, other):
  4103. if "%" in other and not isinstance(other, _anonymous_label):
  4104. other = util.text_type(other).replace("%", "%%")
  4105. else:
  4106. other = util.text_type(other)
  4107. return _anonymous_label(
  4108. quoted_name(
  4109. util.text_type.__add__(other, self),
  4110. self.quote,
  4111. )
  4112. )
  4113. def apply_map(self, map_):
  4114. if self.quote is not None:
  4115. # preserve quoting only if necessary
  4116. return quoted_name(self % map_, self.quote)
  4117. else:
  4118. # else skip the constructor call
  4119. return self % map_