sqldb.pp 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640
  1. {
  2. Copyright (c) 2004-2014 by Joost van der Sluis, FPC contributors
  3. SQL database & dataset
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. unit sqldb;
  11. {$mode objfpc}
  12. {$H+}
  13. {$M+} // ### remove this!!!
  14. interface
  15. uses SysUtils, Classes, DB, bufdataset, sqlscript, sqltypes;
  16. type
  17. TSchemaType = sqltypes.TSchemaType;
  18. TStatementType = sqltypes.TStatementType;
  19. TDBEventType = sqltypes.TDBEventType;
  20. TDBEventTypes = sqltypes.TDBEventTypes;
  21. TQuoteChars = sqltypes.TQuoteChars;
  22. const
  23. StatementTokens : Array[TStatementType] of string = ('(unknown)', 'select',
  24. 'insert', 'update', 'delete',
  25. 'create', 'get', 'put', 'execute',
  26. 'start','commit','rollback', '?'
  27. );
  28. TSchemaObjectNames: array[TSchemaType] of String = ('???', 'table_name',
  29. '???', 'procedure_name', 'column_name', 'param_name',
  30. 'index_name', 'package_name', 'schema_name','sequence');
  31. SingleQuotes : TQuoteChars = ('''','''');
  32. DoubleQuotes : TQuoteChars = ('"','"');
  33. LogAllEvents = [detCustom, detPrepare, detExecute, detFetch, detCommit, detRollBack];
  34. LogAllEventsExtra = [detCustom, detPrepare, detExecute, detFetch, detCommit, detRollBack, detParamValue,detActualSQL];
  35. // Backwards compatibility alias constants.
  36. stNoSchema = sqltypes.stNoSchema;
  37. stTables = sqltypes.stTables;
  38. stSysTables = sqltypes.stSysTables;
  39. stProcedures = sqltypes.stProcedures;
  40. stColumns = sqltypes.stColumns;
  41. stProcedureParams = sqltypes.stProcedureParams;
  42. stIndexes = sqltypes.stIndexes;
  43. stPackages = sqltypes.stPackages;
  44. stSchemata = sqltypes.stSchemata;
  45. stSequences = sqltypes.stSequences;
  46. stUnknown = sqltypes.stUnknown;
  47. stSelect = sqltypes.stSelect;
  48. stInsert = sqltypes.stInsert;
  49. stUpdate = sqltypes.stUpdate;
  50. stDelete = sqltypes.stDelete;
  51. stDDL = sqltypes.stDDL;
  52. stGetSegment = sqltypes.stGetSegment;
  53. stPutSegment = sqltypes.stPutSegment;
  54. stExecProcedure = sqltypes.stExecProcedure;
  55. stStartTrans = sqltypes.stStartTrans;
  56. stCommit = sqltypes.stCommit;
  57. stRollback = sqltypes.stRollback;
  58. stSelectForUpd = sqltypes.stSelectForUpd;
  59. detCustom = sqltypes.detCustom;
  60. detPrepare = sqltypes.detPrepare;
  61. detExecute = sqltypes.detExecute;
  62. detFetch = sqltypes.detFetch;
  63. detCommit = sqltypes.detCommit;
  64. detRollBack = sqltypes.detRollBack;
  65. detParamValue = sqltypes.detParamValue;
  66. detActualSQL = sqltypes.detActualSQL;
  67. Type
  68. TRowsCount = LargeInt;
  69. TSQLStatementInfo = Record
  70. StatementType : TStatementType;
  71. TableName : String;
  72. Updateable : Boolean;
  73. WhereStartPos ,
  74. WhereStopPos : integer;
  75. end;
  76. TSQLConnection = class;
  77. TSQLTransaction = class;
  78. TCustomSQLQuery = class;
  79. TCustomSQLStatement = Class;
  80. TSQLQuery = class;
  81. TSQLScript = class;
  82. TSQLHandle = Class(TObject)
  83. end;
  84. { TSQLCursor }
  85. TSQLCursor = Class(TSQLHandle)
  86. public
  87. FPrepared : Boolean;
  88. FSelectable : Boolean;
  89. FInitFieldDef : Boolean;
  90. FStatementType : TStatementType;
  91. FSchemaType : TSchemaType;
  92. end;
  93. { ESQLDatabaseError}
  94. ESQLDatabaseError = class(EDatabaseError)
  95. public
  96. ErrorCode: integer;
  97. SQLState : string;
  98. constructor CreateFmt(const Fmt: string; const Args: array of const;
  99. Comp : TComponent; AErrorCode: integer; ASQLState: string); overload;
  100. end;
  101. { TSQLDBFieldDef }
  102. TSQLDBFieldDef = Class(TFieldDef)
  103. private
  104. FData: Pointer;
  105. Public
  106. Property SQLDBData : Pointer Read FData Write FData;
  107. end;
  108. { TSQLDBFieldDefs }
  109. TSQLDBFieldDefs = Class(TFieldDefs)
  110. Protected
  111. Class Function FieldDefClass : TFieldDefClass; override;
  112. end;
  113. { TSQLDBParam }
  114. TSQLDBParam = Class(TParam)
  115. private
  116. FFieldDef: TFieldDef;
  117. FData : Pointer;
  118. Public
  119. Property FieldDef : TFieldDef Read FFieldDef Write FFieldDef;
  120. Property SQLDBData : Pointer Read FData Write FData;
  121. end;
  122. { TSQLDBParams }
  123. TSQLDBParams = Class(TParams)
  124. Protected
  125. Class Function ParamClass : TParamClass; override;
  126. end;
  127. type
  128. { TServerIndexDefs }
  129. TServerIndexDefs = class(TIndexDefs)
  130. Private
  131. public
  132. constructor Create(ADataSet: TDataSet); override;
  133. procedure Update; override;
  134. end;
  135. type
  136. { TSQLConnection }
  137. TDBLogNotifyEvent = Procedure (Sender : TSQLConnection; EventType : TDBEventType; Const Msg : String) of object;
  138. TConnOption = (sqSupportParams, sqSupportEmptyDatabaseName, sqEscapeSlash, sqEscapeRepeat, sqImplicitTransaction, sqLastInsertID, sqSupportReturning);
  139. TConnOptions= set of TConnOption;
  140. TSQLConnectionOption = (scoExplicitConnect, scoApplyUpdatesChecksRowsAffected);
  141. TSQLConnectionOptions = Set of TSQLConnectionOption;
  142. TConnInfoType=(citAll=-1, citServerType, citServerVersion, citServerVersionString, citClientName, citClientVersion);
  143. TSQLConnection = class (TDatabase)
  144. private
  145. FFieldNameQuoteChars : TQuoteChars;
  146. FOptions : TSQLConnectionOptions;
  147. FPassword : string;
  148. FTransaction : TSQLTransaction;
  149. FUserName : string;
  150. FHostName : string;
  151. FCharSet : string;
  152. FRole : String;
  153. FStatements : TFPList;
  154. FLogEvents: TDBEventTypes;
  155. FOnLog: TDBLogNotifyEvent;
  156. function GetPort: cardinal;
  157. procedure SetOptions(AValue: TSQLConnectionOptions);
  158. procedure SetPort(const AValue: cardinal);
  159. function AttemptCommit(trans : TSQLHandle) : boolean;
  160. function AttemptRollBack(trans : TSQLHandle) : boolean;
  161. protected
  162. FConnOptions : TConnOptions;
  163. FSQLFormatSettings : TFormatSettings;
  164. // Updating of DB records is moved out of TSQLQuery.
  165. // It is done here, so descendents can override it and implement DB-specific.
  166. // One day, this may be factored out to a TSQLResolver class.
  167. // The following allow construction of update queries. They can be adapted as needed by descendents to fit the DB engine.
  168. procedure AddFieldToUpdateWherePart(var sql_where: string; UpdateMode : TUpdateMode; F: TField); virtual;
  169. function ConstructInsertSQL(Query: TCustomSQLQuery; Var ReturningClause : Boolean): string; virtual;
  170. function ConstructUpdateSQL(Query: TCustomSQLQuery; Var ReturningClause : Boolean): string; virtual;
  171. function ConstructDeleteSQL(Query: TCustomSQLQuery): string; virtual;
  172. function ConstructRefreshSQL(Query: TCustomSQLQuery; UpdateKind : TUpdateKind): string; virtual;
  173. function InitialiseUpdateStatement(Query: TCustomSQLQuery; var qry: TCustomSQLQuery): TCustomSQLQuery;
  174. procedure ApplyFieldUpdate(C : TSQLCursor; P: TSQLDBParam; F: TField; UseOldValue: Boolean); virtual;
  175. // This is the call that updates a record, it used to be in TSQLQuery.
  176. procedure ApplyRecUpdate(Query : TCustomSQLQuery; UpdateKind : TUpdateKind); virtual;
  177. function RefreshLastInsertID(Query : TCustomSQLQuery; Field : TField): Boolean; virtual;
  178. procedure GetDBInfo(const ASchemaType : TSchemaType; const ASchemaObjectName, AReturnField : string; AList: TStrings);
  179. procedure SetTransaction(Value : TSQLTransaction); virtual;
  180. procedure DoInternalConnect; override;
  181. procedure DoInternalDisconnect; override;
  182. function GetAsSQLText(Field : TField) : string; overload; virtual;
  183. function GetAsSQLText(Param : TParam) : string; overload; virtual;
  184. function GetHandle : pointer; virtual;
  185. Function LogEvent(EventType : TDBEventType) : Boolean;
  186. Procedure LogParams(Const AParams : TParams); virtual;
  187. Procedure Log(EventType : TDBEventType; Const Msg : String); virtual;
  188. Procedure RegisterStatement(S : TCustomSQLStatement);
  189. Procedure UnRegisterStatement(S : TCustomSQLStatement);
  190. Function AllocateCursorHandle : TSQLCursor; virtual; abstract;
  191. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); virtual; abstract;
  192. function StrToStatementType(s : string) : TStatementType; virtual;
  193. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); virtual; abstract;
  194. procedure UnPrepareStatement(cursor : TSQLCursor); virtual; abstract;
  195. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); virtual; abstract;
  196. function RowsAffected(cursor: TSQLCursor): TRowsCount; virtual;
  197. function Fetch(cursor : TSQLCursor) : boolean; virtual; abstract;
  198. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); virtual; abstract;
  199. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; virtual; abstract;
  200. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); virtual; abstract;
  201. procedure FreeFldBuffers(cursor : TSQLCursor); virtual;
  202. Function AllocateTransactionHandle : TSQLHandle; virtual; abstract;
  203. function GetTransactionHandle(trans : TSQLHandle): pointer; virtual; abstract;
  204. function Commit(trans : TSQLHandle) : boolean; virtual; abstract;
  205. function RollBack(trans : TSQLHandle) : boolean; virtual; abstract;
  206. function StartImplicitTransaction(trans : TSQLHandle; aParams : string) : boolean; virtual;
  207. function StartDBTransaction(trans : TSQLHandle; aParams : string) : boolean; virtual; abstract;
  208. procedure CommitRetaining(trans : TSQLHandle); virtual; abstract;
  209. procedure RollBackRetaining(trans : TSQLHandle); virtual; abstract;
  210. procedure UpdateIndexDefs(IndexDefs : TIndexDefs; TableName : string); virtual;
  211. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; virtual;
  212. function GetNextValueSQL(const SequenceName: string; IncrementBy: Integer): string; virtual;
  213. Procedure MaybeConnect;
  214. Property Statements : TFPList Read FStatements;
  215. property Port: cardinal read GetPort write SetPort;
  216. public
  217. property Handle: Pointer read GetHandle;
  218. property FieldNameQuoteChars: TQuoteChars read FFieldNameQuoteChars write FFieldNameQuoteChars;
  219. constructor Create(AOwner: TComponent); override;
  220. destructor Destroy; override;
  221. procedure StartTransaction; override;
  222. procedure EndTransaction; override;
  223. procedure ExecuteDirect(SQL : String); overload; virtual;
  224. procedure ExecuteDirect(SQL : String; ATransaction : TSQLTransaction); overload; virtual;
  225. // Unified version
  226. function GetObjectNames(ASchemaType: TSchemaType; AList : TSqlObjectIdentifierList): Integer; virtual;
  227. // Older versions.
  228. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); virtual;
  229. procedure GetProcedureNames(List : TStrings); virtual;
  230. procedure GetFieldNames(const TableName : string; List : TStrings); virtual;
  231. procedure GetSchemaNames(List: TStrings); virtual;
  232. procedure GetSequenceNames(List: TStrings); virtual;
  233. function GetConnectionInfo(InfoType:TConnInfoType): string; virtual;
  234. function GetStatementInfo(const ASQL: string): TSQLStatementInfo; virtual;
  235. procedure CreateDB; virtual;
  236. procedure DropDB; virtual;
  237. function GetNextValue(const SequenceName: string; IncrementBy: integer=1): Int64; virtual;
  238. property ConnOptions: TConnOptions read FConnOptions;
  239. published
  240. property Password : string read FPassword write FPassword;
  241. property Transaction : TSQLTransaction read FTransaction write SetTransaction;
  242. property UserName : string read FUserName write FUserName;
  243. property CharSet : string read FCharSet write FCharSet;
  244. property HostName : string Read FHostName Write FHostName;
  245. Property OnLog : TDBLogNotifyEvent Read FOnLog Write FOnLog;
  246. Property LogEvents : TDBEventTypes Read FLogEvents Write FLogEvents Default LogAllEvents;
  247. Property Options : TSQLConnectionOptions Read FOptions Write SetOptions;
  248. Property Role : String read FRole write FRole;
  249. property Connected;
  250. property DatabaseName;
  251. property KeepConnection;
  252. property LoginPrompt;
  253. property Params;
  254. property OnLogin;
  255. end;
  256. { TSQLTransaction }
  257. TCommitRollbackAction = (caNone, caCommit, caCommitRetaining, caRollback,
  258. caRollbackRetaining);
  259. TSQLTransactionOption = (stoUseImplicit, stoExplicitStart);
  260. TSQLTransactionOptions = Set of TSQLTransactionOption;
  261. TSQLTransaction = class (TDBTransaction)
  262. private
  263. FOptions : TSQLTransactionOptions;
  264. FTrans : TSQLHandle;
  265. FAction : TCommitRollbackAction;
  266. FParams : TStringList;
  267. function GetSQLConnection: TSQLConnection;
  268. procedure SetOptions(AValue: TSQLTransactionOptions);
  269. procedure SetParams(const AValue: TStringList);
  270. procedure SetSQLConnection(AValue: TSQLConnection);
  271. protected
  272. Procedure MaybeStartTransaction;
  273. Function AllowClose(DS: TDBDataset): Boolean; override;
  274. function GetHandle : Pointer; virtual;
  275. Procedure SetDatabase (Value : TDatabase); override;
  276. Function LogEvent(EventType : TDBEventType) : Boolean;
  277. Procedure Log(EventType : TDBEventType; Const Msg : String); virtual;
  278. public
  279. constructor Create(AOwner : TComponent); override;
  280. destructor Destroy; override;
  281. procedure Commit; override;
  282. procedure CommitRetaining; override;
  283. procedure Rollback; override;
  284. procedure RollbackRetaining; override;
  285. procedure StartTransaction; override;
  286. procedure EndTransaction; override;
  287. property Handle: Pointer read GetHandle;
  288. Property SQLConnection : TSQLConnection Read GetSQLConnection Write SetSQLConnection;
  289. published
  290. property Action : TCommitRollbackAction read FAction write FAction Default caRollBack;
  291. property Database;
  292. property Params : TStringList read FParams write SetParams;
  293. Property Options : TSQLTransactionOptions Read FOptions Write SetOptions;
  294. end;
  295. { TCustomSQLStatement }
  296. TCustomSQLStatement = Class(TComponent)
  297. Private
  298. FCursor : TSQLCursor;
  299. FDatabase: TSQLConnection;
  300. FParamCheck: Boolean;
  301. FParams: TParams;
  302. FSQL: TStrings;
  303. FOrigSQL : String;
  304. FServerSQL : String;
  305. FTransaction: TSQLTransaction;
  306. FParseSQL: Boolean;
  307. FDataLink : TDataLink;
  308. FRowsAffected : TRowsCount;
  309. procedure SetDatabase(AValue: TSQLConnection);
  310. procedure SetParams(AValue: TParams);
  311. procedure SetSQL(AValue: TStrings);
  312. procedure SetTransaction(AValue: TSQLTransaction);
  313. Function GetPrepared : Boolean;
  314. Protected
  315. Function CreateDataLink : TDataLink; virtual;
  316. procedure OnChangeSQL(Sender : TObject); virtual;
  317. function GetDataSource: TDataSource; Virtual;
  318. procedure SetDataSource(AValue: TDataSource); virtual;
  319. Procedure CopyParamsFromMaster(CopyBound : Boolean); virtual;
  320. procedure AllocateCursor;
  321. procedure DeAllocateCursor;
  322. Function GetSchemaType : TSchemaType; virtual;
  323. Function GetSchemaObjectName : String; virtual;
  324. Function GetSchemaPattern: String; virtual;
  325. Function IsSelectable : Boolean ; virtual;
  326. procedure GetStatementInfo(var ASQL: String; out Info: TSQLStatementInfo); virtual;
  327. Procedure DoExecute; virtual;
  328. procedure DoPrepare; virtual;
  329. procedure DoUnPrepare; virtual;
  330. Function CreateParams : TSQLDBParams; virtual;
  331. Function LogEvent(EventType : TDBEventType) : Boolean;
  332. Procedure Log(EventType : TDBEventType; Const Msg : String); virtual;
  333. procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  334. Property Cursor : TSQLCursor read FCursor;
  335. Property Database : TSQLConnection Read FDatabase Write SetDatabase;
  336. Property Transaction : TSQLTransaction Read FTransaction Write SetTransaction;
  337. Property SQL : TStrings Read FSQL Write SetSQL;
  338. Property Params : TParams Read FParams Write SetParams;
  339. Property DataSource : TDataSource Read GetDataSource Write SetDataSource;
  340. Property ParseSQL : Boolean Read FParseSQL Write FParseSQL;
  341. Property ParamCheck : Boolean Read FParamCheck Write FParamCheck default true;
  342. Public
  343. constructor Create(AOwner : TComponent); override;
  344. destructor Destroy; override;
  345. Procedure Prepare;
  346. Procedure Execute;
  347. Procedure Unprepare;
  348. function ParamByName(Const AParamName : String) : TParam;
  349. function RowsAffected: TRowsCount; virtual;
  350. Property Prepared : boolean read GetPrepared;
  351. end;
  352. TSQLStatement = Class(TCustomSQLStatement)
  353. Published
  354. Property Database;
  355. Property DataSource;
  356. Property ParamCheck;
  357. Property Params;
  358. Property ParseSQL;
  359. Property SQL;
  360. Property Transaction;
  361. end;
  362. { TSQLSequence }
  363. TSQLSequenceApplyEvent = (saeOnNewRecord, saeOnPost);
  364. TSQLSequence = class(TPersistent)
  365. private
  366. FQuery: TCustomSQLQuery;
  367. FFieldName: String;
  368. FSequenceName: String;
  369. FIncrementBy: Integer;
  370. FApplyEvent: TSQLSequenceApplyEvent;
  371. public
  372. constructor Create(AQuery: TCustomSQLQuery);
  373. procedure Assign(Source: TPersistent); override;
  374. procedure Apply;
  375. function GetNextValue: Int64;
  376. published
  377. property FieldName: String read FFieldName write FFieldName;
  378. property SequenceName: String read FSequenceName write FSequenceName;
  379. property IncrementBy: Integer read FIncrementBy write FIncrementBy default 1;
  380. property ApplyEvent: TSQLSequenceApplyEvent read FApplyEvent write FApplyEvent default saeOnNewRecord;
  381. end;
  382. { TCustomSQLQuery }
  383. TSQLQueryOption = (sqoKeepOpenOnCommit, sqoAutoApplyUpdates, sqoAutoCommit, sqoCancelUpdatesOnRefresh, sqoRefreshUsingSelect);
  384. TSQLQueryOptions = Set of TSQLQueryOption;
  385. TCustomSQLQuery = class (TCustomBufDataset)
  386. private
  387. FOptions : TSQLQueryOptions;
  388. FSchemaType : TSchemaType;
  389. FUpdateable : boolean;
  390. FTableName : string;
  391. FStatement : TCustomSQLStatement;
  392. FInsertSQL,
  393. FUpdateSQL,
  394. FDeleteSQL,
  395. FRefreshSQL : TStringList;
  396. FIsEOF : boolean;
  397. FLoadingFieldDefs : boolean;
  398. FUpdateMode : TUpdateMode;
  399. FusePrimaryKeyAsKey : Boolean;
  400. FWhereStartPos : integer;
  401. FWhereStopPos : integer;
  402. FServerFilterText : string;
  403. FServerFiltered : Boolean;
  404. FServerIndexDefs : TServerIndexDefs;
  405. // Used by SetSchemaType
  406. FSchemaObjectName : string;
  407. FSchemaPattern : string;
  408. FInsertQry,
  409. FUpdateQry,
  410. FDeleteQry : TCustomSQLQuery;
  411. FSequence : TSQLSequence;
  412. procedure FreeFldBuffers;
  413. function GetParamCheck: Boolean;
  414. function GetParams: TParams;
  415. function GetParseSQL: Boolean;
  416. function GetServerIndexDefs: TServerIndexDefs;
  417. function GetSQL: TStringList;
  418. function GetSQLConnection: TSQLConnection;
  419. function GetSQLTransaction: TSQLTransaction;
  420. function GetStatementType : TStatementType;
  421. Function NeedLastInsertID: TField;
  422. procedure SetOptions(AValue: TSQLQueryOptions);
  423. procedure SetParamCheck(AValue: Boolean);
  424. procedure SetSQLConnection(AValue: TSQLConnection);
  425. procedure SetSQLTransaction(AValue: TSQLTransaction);
  426. procedure SetInsertSQL(const AValue: TStringList);
  427. procedure SetUpdateSQL(const AValue: TStringList);
  428. procedure SetDeleteSQL(const AValue: TStringList);
  429. procedure SetRefreshSQL(const AValue: TStringList);
  430. procedure SetParams(AValue: TParams);
  431. procedure SetParseSQL(AValue : Boolean);
  432. procedure SetSQL(const AValue: TStringList);
  433. procedure SetUsePrimaryKeyAsKey(AValue : Boolean);
  434. procedure SetUpdateMode(AValue : TUpdateMode);
  435. procedure OnChangeModifySQL(Sender : TObject);
  436. procedure Execute;
  437. procedure ApplyFilter;
  438. Function AddFilter(SQLstr : string) : string;
  439. protected
  440. Function RefreshLastInsertID(Field: TField): Boolean; virtual;
  441. Function NeedRefreshRecord (UpdateKind: TUpdateKind): Boolean; virtual;
  442. Function RefreshRecord (UpdateKind: TUpdateKind) : Boolean; virtual;
  443. Procedure ApplyReturningResult(Q : TCustomSQLQuery; UpdateKind : TUpdateKind);
  444. Function Cursor : TSQLCursor;
  445. Function LogEvent(EventType : TDBEventType) : Boolean;
  446. Procedure Log(EventType : TDBEventType; Const Msg : String); virtual;
  447. // abstract & virtual methods of TBufDataset
  448. function Fetch : boolean; override;
  449. function LoadField(FieldDef : TFieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  450. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField); override;
  451. procedure ApplyRecUpdate(UpdateKind : TUpdateKind); override;
  452. procedure SetPacketRecords(aValue : integer); override;
  453. // abstract & virtual methods of TDataset
  454. procedure UpdateServerIndexDefs; virtual;
  455. procedure SetDatabase(Value : TDatabase); override;
  456. Procedure SetTransaction(Value : TDBTransaction); override;
  457. procedure InternalAddRecord(Buffer: Pointer; AAppend: Boolean); override;
  458. procedure InternalClose; override;
  459. procedure InternalInitFieldDefs; override;
  460. procedure InternalOpen; override;
  461. Procedure InternalRefresh; override;
  462. function GetCanModify: Boolean; override;
  463. Function IsPrepared : Boolean; virtual;
  464. Procedure SetActive (Value : Boolean); override;
  465. procedure SetServerFiltered(Value: Boolean); virtual;
  466. procedure SetServerFilterText(const Value: string); virtual;
  467. Function GetDataSource : TDataSource; override;
  468. Procedure SetDataSource(AValue : TDataSource);
  469. procedure BeforeRefreshOpenCursor; override;
  470. procedure SetReadOnly(AValue : Boolean); override;
  471. procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  472. procedure DoOnNewRecord; override;
  473. procedure DoBeforePost; override;
  474. class function FieldDefsClass : TFieldDefsClass; override;
  475. // IProviderSupport methods
  476. function PSGetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError; override;
  477. function PSGetTableName: string; override;
  478. Property TableName : String Read FTableName Write FTableName; // alternative: procedure DoGetTableName
  479. public
  480. constructor Create(AOwner : TComponent); override;
  481. destructor Destroy; override;
  482. procedure Prepare; virtual;
  483. procedure UnPrepare; virtual;
  484. procedure ExecSQL; virtual;
  485. procedure SetSchemaInfo( ASchemaType : TSchemaType; ASchemaObjectName, ASchemaPattern : string); virtual;
  486. function RowsAffected: TRowsCount; virtual;
  487. function ParamByName(Const AParamName : String) : TParam;
  488. Property Prepared : boolean read IsPrepared;
  489. Property SQLConnection : TSQLConnection Read GetSQLConnection Write SetSQLConnection;
  490. Property SQLTransaction: TSQLTransaction Read GetSQLTransaction Write SetSQLTransaction;
  491. // overriden TBufDataSet methods
  492. Procedure ApplyUpdates(MaxErrors: Integer); override; overload;
  493. // overriden TDataSet methods
  494. Procedure Post; override;
  495. Procedure Delete; override;
  496. protected
  497. // redeclared TDataSet properties
  498. property Active;
  499. property Filter;
  500. property Filtered;
  501. property BeforeOpen;
  502. property AfterOpen;
  503. property BeforeClose;
  504. property AfterClose;
  505. property BeforeInsert;
  506. property AfterInsert;
  507. property BeforeEdit;
  508. property AfterEdit;
  509. property BeforePost;
  510. property AfterPost;
  511. property BeforeCancel;
  512. property AfterCancel;
  513. property BeforeDelete;
  514. property AfterDelete;
  515. property BeforeScroll;
  516. property AfterScroll;
  517. property OnCalcFields;
  518. property OnDeleteError;
  519. property OnEditError;
  520. property OnFilterRecord;
  521. property OnNewRecord;
  522. property OnPostError;
  523. property AutoCalcFields;
  524. // protected
  525. property Database;
  526. property Transaction;
  527. property SchemaType : TSchemaType read FSchemaType default stNoSchema;
  528. property SQL : TStringlist read GetSQL write SetSQL;
  529. property InsertSQL : TStringList read FInsertSQL write SetInsertSQL;
  530. property UpdateSQL : TStringList read FUpdateSQL write SetUpdateSQL;
  531. property DeleteSQL : TStringList read FDeleteSQL write SetDeleteSQL;
  532. property RefreshSQL : TStringList read FRefreshSQL write SetRefreshSQL;
  533. Property Options : TSQLQueryOptions Read FOptions Write SetOptions;
  534. property Params : TParams read GetParams Write SetParams;
  535. Property ParamCheck : Boolean Read GetParamCheck Write SetParamCheck default true;
  536. property ParseSQL : Boolean read GetParseSQL write SetParseSQL default true;
  537. property UpdateMode : TUpdateMode read FUpdateMode write SetUpdateMode default upWhereKeyOnly;
  538. property UsePrimaryKeyAsKey : boolean read FUsePrimaryKeyAsKey write SetUsePrimaryKeyAsKey default true;
  539. property StatementType : TStatementType read GetStatementType;
  540. Property DataSource : TDataSource Read GetDataSource Write SetDataSource;
  541. property Sequence: TSQLSequence read FSequence write FSequence;
  542. property ServerFilter: string read FServerFilterText write SetServerFilterText;
  543. property ServerFiltered: Boolean read FServerFiltered write SetServerFiltered default False;
  544. property ServerIndexDefs : TServerIndexDefs read GetServerIndexDefs;
  545. end;
  546. { TSQLQuery }
  547. TSQLQuery = Class(TCustomSQLQuery)
  548. public
  549. property SchemaType;
  550. Property StatementType;
  551. Published
  552. property MaxIndexesCount;
  553. // TDataset stuff
  554. property FieldDefs;
  555. Property Active;
  556. Property AutoCalcFields;
  557. Property Filter;
  558. Property Filtered;
  559. Property AfterCancel;
  560. Property AfterClose;
  561. Property AfterDelete;
  562. Property AfterEdit;
  563. Property AfterInsert;
  564. Property AfterOpen;
  565. Property AfterPost;
  566. Property AfterScroll;
  567. Property BeforeCancel;
  568. Property BeforeClose;
  569. Property BeforeDelete;
  570. Property BeforeEdit;
  571. Property BeforeInsert;
  572. Property BeforeOpen;
  573. Property BeforePost;
  574. Property BeforeScroll;
  575. Property OnCalcFields;
  576. Property OnDeleteError;
  577. Property OnEditError;
  578. Property OnFilterRecord;
  579. Property OnNewRecord;
  580. Property OnPostError;
  581. // property SchemaInfo default stNoSchema;
  582. property Database;
  583. property Transaction;
  584. property ReadOnly;
  585. property SQL;
  586. property InsertSQL;
  587. property UpdateSQL;
  588. property DeleteSQL;
  589. property RefreshSQL;
  590. property IndexDefs;
  591. Property Options;
  592. property Params;
  593. Property ParamCheck;
  594. property ParseSQL;
  595. property UpdateMode;
  596. property UsePrimaryKeyAsKey;
  597. Property DataSource;
  598. property Sequence;
  599. property ServerFilter;
  600. property ServerFiltered;
  601. property ServerIndexDefs;
  602. end;
  603. { TSQLScript }
  604. TSQLScript = class (TCustomSQLscript)
  605. private
  606. FOnDirective: TSQLScriptDirectiveEvent;
  607. FQuery : TCustomSQLQuery;
  608. FDatabase : TDatabase;
  609. FTransaction : TDBTransaction;
  610. protected
  611. procedure ExecuteStatement (SQLStatement: TStrings; var StopExecution: Boolean); override;
  612. procedure ExecuteDirective (Directive, Argument: String; var StopExecution: Boolean); override;
  613. procedure ExecuteCommit(CommitRetaining: boolean=true); override;
  614. Procedure SetDatabase (Value : TDatabase); virtual;
  615. Procedure SetTransaction(Value : TDBTransaction); virtual;
  616. Procedure CheckDatabase;
  617. public
  618. constructor Create(AOwner : TComponent); override;
  619. destructor Destroy; override;
  620. procedure Execute; override;
  621. procedure ExecuteScript;
  622. published
  623. Property DataBase : TDatabase Read FDatabase Write SetDatabase;
  624. Property Transaction : TDBTransaction Read FTransaction Write SetTransaction;
  625. property OnDirective: TSQLScriptDirectiveEvent read FOnDirective write FOnDirective;
  626. property Directives;
  627. property Defines;
  628. property Script;
  629. property Terminator;
  630. property CommentsinSQL;
  631. property UseSetTerm;
  632. property UseCommit;
  633. property UseDefines;
  634. property OnException;
  635. end;
  636. { TSQLConnector }
  637. TSQLConnector = Class(TSQLConnection)
  638. private
  639. FProxy : TSQLConnection;
  640. FConnectorType: String;
  641. procedure SetConnectorType(const AValue: String);
  642. protected
  643. procedure SetTransaction(Value : TSQLTransaction);override;
  644. procedure DoInternalConnect; override;
  645. procedure DoInternalDisconnect; override;
  646. Procedure CheckProxy;
  647. Procedure CreateProxy; virtual;
  648. Procedure FreeProxy; virtual;
  649. function StrToStatementType(s : string) : TStatementType; override;
  650. function GetAsSQLText(Field : TField) : string; overload; override;
  651. function GetAsSQLText(Param : TParam) : string; overload; override;
  652. function GetHandle : pointer; override;
  653. Function AllocateCursorHandle : TSQLCursor; override;
  654. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); override;
  655. Function AllocateTransactionHandle : TSQLHandle; override;
  656. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); override;
  657. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); override;
  658. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  659. function Fetch(cursor : TSQLCursor) : boolean; override;
  660. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); override;
  661. procedure UnPrepareStatement(cursor : TSQLCursor); override;
  662. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer; out CreateBlob : boolean) : boolean; override;
  663. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef;ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction : TSQLTransaction); override;
  664. procedure FreeFldBuffers(cursor : TSQLCursor); override;
  665. function GetTransactionHandle(trans : TSQLHandle): pointer; override;
  666. function Commit(trans : TSQLHandle) : boolean; override;
  667. function RollBack(trans : TSQLHandle) : boolean; override;
  668. function StartDBTransaction(trans : TSQLHandle; aParams : string) : boolean; override;
  669. procedure CommitRetaining(trans : TSQLHandle); override;
  670. procedure RollBackRetaining(trans : TSQLHandle); override;
  671. procedure UpdateIndexDefs(IndexDefs : TIndexDefs; TableName : string); override;
  672. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  673. Property Proxy : TSQLConnection Read FProxy;
  674. Published
  675. Property ConnectorType : String Read FConnectorType Write SetConnectorType;
  676. end;
  677. TSQLConnectionClass = Class of TSQLConnection;
  678. { TConnectionDef }
  679. TLibraryLoadFunction = Function (Const S : AnsiString) : Integer;
  680. TLibraryUnLoadFunction = Procedure;
  681. TConnectionDef = Class(TPersistent)
  682. Class Function TypeName : String; virtual;
  683. Class Function ConnectionClass : TSQLConnectionClass; virtual;
  684. Class Function Description : String; virtual;
  685. Class Function DefaultLibraryName : String; virtual;
  686. Class Function LoadFunction : TLibraryLoadFunction; virtual;
  687. Class Function UnLoadFunction : TLibraryUnLoadFunction; virtual;
  688. Class Function LoadedLibraryName : string; virtual;
  689. Procedure ApplyParams(Params : TStrings; AConnection : TSQLConnection); virtual;
  690. end;
  691. TConnectionDefClass = class of TConnectionDef;
  692. Var
  693. GlobalDBLogHook : TDBLogNotifyEvent;
  694. Procedure RegisterConnection(Def : TConnectionDefClass);
  695. Procedure UnRegisterConnection(Def : TConnectionDefClass);
  696. Procedure UnRegisterConnection(ConnectionName : String);
  697. Function GetConnectionDef(ConnectorName : String) : TConnectionDef;
  698. Procedure GetConnectionList(List : TSTrings);
  699. const DefaultSQLFormatSettings : TFormatSettings = (
  700. CurrencyFormat: 1;
  701. NegCurrFormat: 5;
  702. ThousandSeparator: #0;
  703. DecimalSeparator: '.';
  704. CurrencyDecimals: 2;
  705. DateSeparator: '-';
  706. TimeSeparator: ':';
  707. ListSeparator: ' ';
  708. CurrencyString: '$';
  709. ShortDateFormat: 'yyyy-mm-dd';
  710. LongDateFormat: '';
  711. TimeAMString: '';
  712. TimePMString: '';
  713. ShortTimeFormat: 'hh:nn:ss';
  714. LongTimeFormat: 'hh:nn:ss.zzz';
  715. ShortMonthNames: ('','','','','','','','','','','','');
  716. LongMonthNames: ('','','','','','','','','','','','');
  717. ShortDayNames: ('','','','','','','');
  718. LongDayNames: ('','','','','','','');
  719. TwoDigitYearCenturyWindow: 50;
  720. );
  721. implementation
  722. uses dbconst, strutils;
  723. Const
  724. // Flags to check which fields must be refreshed.
  725. RefreshFlags : Array [ukModify..ukInsert] of TProviderFlag = (pfRefreshOnUpdate,pfRefreshOnInsert);
  726. function TimeIntervalToString(Time: TDateTime): string;
  727. var
  728. millisecond: word;
  729. second : word;
  730. minute : word;
  731. hour : word;
  732. begin
  733. DecodeTime(Time,hour,minute,second,millisecond);
  734. hour := hour + trunc(Time)*24;
  735. Result := Format('%.2d:%.2d:%.2d.%.3d',[hour,minute,second,millisecond]);
  736. end;
  737. { TSQLDBFieldDefs }
  738. class function TSQLDBFieldDefs.FieldDefClass: TFieldDefClass;
  739. begin
  740. Result:=TSQLDBFieldDef;
  741. end;
  742. { TSQLDBParams }
  743. class function TSQLDBParams.ParamClass: TParamClass;
  744. begin
  745. Result:=TSQLDBParam;
  746. end;
  747. { ESQLDatabaseError }
  748. constructor ESQLDatabaseError.CreateFmt(const Fmt: string; const Args: array of const;
  749. Comp: TComponent; AErrorCode: integer; ASQLState: string);
  750. const CompNameFmt='%s : %s';
  751. var Msg: string;
  752. begin
  753. if not assigned(Comp) then
  754. Msg := Fmt
  755. else if Comp.Name = '' then
  756. Msg := Format(CompNameFmt, [Comp.ClassName,Fmt])
  757. else
  758. Msg := Format(CompNameFmt, [Comp.Name,Fmt]);
  759. if Length(Args) = 0 then
  760. inherited Create(Msg)
  761. else
  762. inherited CreateFmt(Msg, Args);
  763. ErrorCode := AErrorCode;
  764. SQLState := ASQLState;
  765. end;
  766. { TCustomSQLStatement }
  767. procedure TCustomSQLStatement.OnChangeSQL(Sender: TObject);
  768. var
  769. ConnOptions : TConnOptions;
  770. NewParams: TSQLDBParams;
  771. begin
  772. UnPrepare;
  773. if not ParamCheck then
  774. exit;
  775. if assigned(DataBase) then
  776. ConnOptions:=DataBase.ConnOptions
  777. else
  778. ConnOptions := [sqEscapeRepeat,sqEscapeSlash];
  779. NewParams := CreateParams;
  780. try
  781. NewParams.ParseSQL(FSQL.Text, True, sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions, psInterbase);
  782. NewParams.AssignValues(FParams);
  783. FParams.Assign(NewParams);
  784. finally
  785. NewParams.Free;
  786. end;
  787. end;
  788. procedure TCustomSQLStatement.SetDatabase(AValue: TSQLConnection);
  789. begin
  790. if FDatabase=AValue then Exit;
  791. UnPrepare;
  792. If Assigned(FDatabase) then
  793. begin
  794. FDatabase.UnregisterStatement(Self);
  795. FDatabase.RemoveFreeNotification(Self);
  796. end;
  797. FDatabase:=AValue;
  798. If Assigned(FDatabase) then
  799. begin
  800. FDatabase.FreeNotification(Self);
  801. FDatabase.RegisterStatement(Self);
  802. if Assigned(Database.Transaction) and (not Assigned(Transaction) or (Transaction.DataBase <> Database)) then
  803. Transaction := Database.Transaction;
  804. OnChangeSQL(Self);
  805. end;
  806. end;
  807. procedure TCustomSQLStatement.SetTransaction(AValue: TSQLTransaction);
  808. begin
  809. if FTransaction=AValue then Exit;
  810. UnPrepare;
  811. if Assigned(FTransaction) then
  812. FTransaction.RemoveFreeNotification(Self);
  813. FTransaction:=AValue;
  814. if Assigned(FTransaction) then
  815. begin
  816. FTransaction.FreeNotification(Self);
  817. if Assigned(Transaction.DataBase) and (Database <> Transaction.DataBase) then
  818. Database := Transaction.DataBase as TSQLConnection;
  819. end;
  820. end;
  821. procedure TCustomSQLStatement.SetDataSource(AValue: TDataSource);
  822. begin
  823. if GetDataSource=AValue then Exit;
  824. if (FDataLink=Nil) then
  825. FDataLink:=CreateDataLink;
  826. FDataLink.DataSource:=AValue;
  827. end;
  828. Procedure TCustomSQLStatement.CopyParamsFromMaster(CopyBound: Boolean);
  829. begin
  830. if Assigned(DataSource) and Assigned(DataSource.Dataset) then
  831. FParams.CopyParamValuesFromDataset(DataSource.Dataset,CopyBound);
  832. end;
  833. procedure TCustomSQLStatement.SetParams(AValue: TParams);
  834. begin
  835. if FParams=AValue then Exit;
  836. FParams.Assign(AValue);
  837. end;
  838. procedure TCustomSQLStatement.SetSQL(AValue: TStrings);
  839. begin
  840. if FSQL=AValue then Exit;
  841. FSQL.Assign(AValue);
  842. end;
  843. Procedure TCustomSQLStatement.DoExecute;
  844. begin
  845. FRowsAffected:=-1;
  846. If (FParams.Count>0) and Assigned(DataSource) then
  847. CopyParamsFromMaster(False);
  848. If LogEvent(detExecute) then
  849. Log(detExecute,FServerSQL);
  850. Database.Execute(FCursor,Transaction, FParams);
  851. end;
  852. Function TCustomSQLStatement.GetPrepared: Boolean;
  853. begin
  854. Result := Assigned(FCursor) and FCursor.FPrepared;
  855. end;
  856. Function TCustomSQLStatement.CreateDataLink: TDataLink;
  857. begin
  858. Result:=TDataLink.Create;
  859. end;
  860. Function TCustomSQLStatement.CreateParams: TSQLDBParams;
  861. begin
  862. Result:=TSQLDBParams.Create(Nil);
  863. end;
  864. Function TCustomSQLStatement.LogEvent(EventType: TDBEventType): Boolean;
  865. begin
  866. Result:=Assigned(Database) and Database.LogEvent(EventType);
  867. end;
  868. Procedure TCustomSQLStatement.Log(EventType: TDBEventType; Const Msg: String);
  869. Var
  870. M : String;
  871. begin
  872. If LogEvent(EventType) then
  873. begin
  874. If (Name<>'') then
  875. M:=Name
  876. else
  877. M:=ClassName;
  878. Database.Log(EventType,M+' : '+Msg);
  879. end;
  880. end;
  881. procedure TCustomSQLStatement.Notification(AComponent: TComponent;
  882. Operation: TOperation);
  883. begin
  884. inherited Notification(AComponent, Operation);
  885. if (operation=opRemove) then
  886. If (AComponent=FTransaction) then
  887. FTransaction:=Nil
  888. else if (AComponent=FDatabase) then
  889. begin
  890. UnPrepare;
  891. FDatabase:=Nil;
  892. end;
  893. end;
  894. constructor TCustomSQLStatement.Create(AOwner: TComponent);
  895. begin
  896. inherited Create(AOwner);
  897. FSQL:=TStringList.Create;
  898. TStringList(FSQL).OnChange:=@OnChangeSQL;
  899. FParams:=CreateParams;
  900. FParamCheck:=True;
  901. FParseSQL:=True;
  902. FRowsAffected:=-1;
  903. end;
  904. destructor TCustomSQLStatement.Destroy;
  905. begin
  906. UnPrepare;
  907. Transaction:=Nil;
  908. Database:=Nil;
  909. DataSource:=Nil;
  910. FreeAndNil(FDataLink);
  911. FreeAndNil(FParams);
  912. FreeAndNil(FSQL);
  913. inherited Destroy;
  914. end;
  915. Function TCustomSQLStatement.GetSchemaType: TSchemaType;
  916. begin
  917. Result:=stNoSchema
  918. end;
  919. Function TCustomSQLStatement.GetSchemaObjectName: String;
  920. begin
  921. Result:='';
  922. end;
  923. Function TCustomSQLStatement.GetSchemaPattern: String;
  924. begin
  925. Result:='';
  926. end;
  927. Function TCustomSQLStatement.IsSelectable: Boolean;
  928. begin
  929. Result:=False;
  930. end;
  931. procedure TCustomSQLStatement.GetStatementInfo(var ASQL: String; out Info: TSQLStatementInfo);
  932. begin
  933. Info:=Database.GetStatementInfo(ASQL);
  934. end;
  935. procedure TCustomSQLStatement.AllocateCursor;
  936. begin
  937. if not assigned(FCursor) then
  938. // Do this as late as possible.
  939. FCursor:=Database.AllocateCursorHandle;
  940. end;
  941. procedure TCustomSQLStatement.DeAllocateCursor;
  942. begin
  943. if Assigned(FCursor) and Assigned(Database) then
  944. DataBase.DeAllocateCursorHandle(FCursor);
  945. end;
  946. procedure TCustomSQLStatement.DoPrepare;
  947. var
  948. StmInfo: TSQLStatementInfo;
  949. begin
  950. if GetSchemaType=stNoSchema then
  951. FOrigSQL := TrimRight(FSQL.Text)
  952. else
  953. FOrigSQL := Database.GetSchemaInfoSQL(GetSchemaType, GetSchemaObjectName, GetSchemaPattern);
  954. if (FOrigSQL='') then
  955. DatabaseError(SErrNoStatement);
  956. FServerSQL:=FOrigSQL;
  957. GetStatementInfo(FServerSQL,StmInfo);
  958. AllocateCursor;
  959. FCursor.FSelectable:=True; // let PrepareStatement and/or Execute alter it
  960. FCursor.FStatementType:=StmInfo.StatementType;
  961. FCursor.FSchemaType:=GetSchemaType;
  962. If LogEvent(detPrepare) then
  963. Log(detPrepare,FServerSQL);
  964. Database.PrepareStatement(FCursor,Transaction,FServerSQL,FParams);
  965. end;
  966. Procedure TCustomSQLStatement.Prepare;
  967. begin
  968. if Prepared then exit;
  969. if not assigned(Database) then
  970. DatabaseError(SErrDatabasenAssigned);
  971. if not assigned(Transaction) then
  972. DatabaseError(SErrTransactionnSet);
  973. Database.MaybeConnect;
  974. if not Transaction.Active then
  975. Transaction.MaybeStartTransaction;
  976. try
  977. DoPrepare;
  978. except
  979. DeAllocateCursor;
  980. Raise;
  981. end;
  982. end;
  983. Procedure TCustomSQLStatement.Execute;
  984. begin
  985. Prepare;
  986. DoExecute;
  987. end;
  988. procedure TCustomSQLStatement.DoUnPrepare;
  989. begin
  990. If Assigned(FCursor) then
  991. If Assigned(Database) then
  992. begin
  993. DataBase.UnPrepareStatement(FCursor);
  994. DeAllocateCursor;
  995. end
  996. else // this should never happen. It means a cursor handle leaks in the DB itself.
  997. FreeAndNil(FCursor);
  998. end;
  999. function TCustomSQLStatement.GetDataSource: TDataSource;
  1000. begin
  1001. if Assigned(FDataLink) then
  1002. Result:=FDataLink.DataSource
  1003. else
  1004. Result:=Nil;
  1005. end;
  1006. Procedure TCustomSQLStatement.Unprepare;
  1007. begin
  1008. // Some SQLConnections does not support statement [un]preparation, but they have allocated local cursor(s)
  1009. // so let them do cleanup f.e. cancel pending queries and/or free resultset
  1010. // and also do UnRegisterStatement!
  1011. if assigned(FCursor) then
  1012. DoUnprepare;
  1013. end;
  1014. function TCustomSQLStatement.ParamByName(Const AParamName: String): TParam;
  1015. begin
  1016. Result:=FParams.ParamByName(AParamName);
  1017. end;
  1018. function TCustomSQLStatement.RowsAffected: TRowsCount;
  1019. begin
  1020. if FRowsAffected=-1 then
  1021. begin
  1022. if Assigned(Database) then
  1023. FRowsAffected:=Database.RowsAffected(FCursor);
  1024. end;
  1025. Result:=FRowsAffected;
  1026. end;
  1027. { TSQLConnection }
  1028. constructor TSQLConnection.Create(AOwner: TComponent);
  1029. begin
  1030. inherited Create(AOwner);
  1031. FSQLFormatSettings:=DefaultSQLFormatSettings;
  1032. FFieldNameQuoteChars:=DoubleQuotes;
  1033. FLogEvents:=LogAllEvents; //match Property LogEvents...Default LogAllEvents
  1034. FStatements:=TFPList.Create;
  1035. end;
  1036. destructor TSQLConnection.Destroy;
  1037. begin
  1038. Connected:=False; // needed because we want to de-allocate statements
  1039. FreeAndNil(FStatements);
  1040. inherited Destroy;
  1041. end;
  1042. function TSQLConnection.StrToStatementType(s : string) : TStatementType;
  1043. var T : TStatementType;
  1044. begin
  1045. S:=Lowercase(s);
  1046. for T:=stSelect to stRollback do
  1047. if (S=StatementTokens[T]) then
  1048. Exit(T);
  1049. Result:=stUnknown;
  1050. end;
  1051. procedure TSQLConnection.SetTransaction(Value : TSQLTransaction);
  1052. begin
  1053. if FTransaction<>value then
  1054. begin
  1055. if Assigned(FTransaction) and FTransaction.Active then
  1056. DatabaseError(SErrAssTransaction);
  1057. if Assigned(Value) then
  1058. Value.Database := Self;
  1059. FTransaction := Value;
  1060. If Assigned(FTransaction) and (FTransaction.Database=Nil) then
  1061. FTransaction.Database:=Self;
  1062. end;
  1063. end;
  1064. procedure TSQLConnection.UpdateIndexDefs(IndexDefs : TIndexDefs; TableName : string);
  1065. begin
  1066. // Empty abstract
  1067. end;
  1068. procedure TSQLConnection.DoInternalConnect;
  1069. begin
  1070. if (DatabaseName = '') and not(sqSupportEmptyDatabaseName in FConnOptions) then
  1071. DatabaseError(SErrNoDatabaseName,self);
  1072. end;
  1073. procedure TSQLConnection.DoInternalDisconnect;
  1074. Var
  1075. I : integer;
  1076. begin
  1077. For I:=0 to FStatements.Count-1 do
  1078. TCustomSQLStatement(FStatements[i]).Unprepare;
  1079. FStatements.Clear;
  1080. end;
  1081. procedure TSQLConnection.StartTransaction;
  1082. begin
  1083. if not assigned(Transaction) then
  1084. DatabaseError(SErrConnTransactionnSet)
  1085. else
  1086. Transaction.StartTransaction;
  1087. end;
  1088. procedure TSQLConnection.EndTransaction;
  1089. begin
  1090. if not assigned(Transaction) then
  1091. DatabaseError(SErrConnTransactionnSet)
  1092. else
  1093. Transaction.EndTransaction;
  1094. end;
  1095. procedure TSQLConnection.ExecuteDirect(SQL: String);
  1096. begin
  1097. ExecuteDirect(SQL,FTransaction);
  1098. end;
  1099. procedure TSQLConnection.ExecuteDirect(SQL: String;
  1100. ATransaction: TSQLTransaction);
  1101. var Cursor : TSQLCursor;
  1102. begin
  1103. if not assigned(ATransaction) then
  1104. DatabaseError(SErrTransactionnSet);
  1105. if not Connected then Open;
  1106. if not ATransaction.Active then
  1107. ATransaction.MaybeStartTransaction;
  1108. SQL := TrimRight(SQL);
  1109. if SQL = '' then
  1110. DatabaseError(SErrNoStatement);
  1111. try
  1112. Cursor := AllocateCursorHandle;
  1113. Cursor.FStatementType := stUnknown;
  1114. If LogEvent(detPrepare) then
  1115. Log(detPrepare,SQL);
  1116. PrepareStatement(Cursor,ATransaction,SQL,Nil);
  1117. try
  1118. If LogEvent(detExecute) then
  1119. Log(detExecute,SQL);
  1120. Execute(Cursor,ATransaction, Nil);
  1121. finally
  1122. UnPrepareStatement(Cursor);
  1123. end;
  1124. finally;
  1125. DeAllocateCursorHandle(Cursor);
  1126. end;
  1127. end;
  1128. function TSQLConnection.GetPort: cardinal;
  1129. begin
  1130. result := StrToIntDef(Params.Values['Port'],0);
  1131. end;
  1132. procedure TSQLConnection.SetOptions(AValue: TSQLConnectionOptions);
  1133. begin
  1134. if FOptions=AValue then Exit;
  1135. FOptions:=AValue;
  1136. end;
  1137. procedure TSQLConnection.SetPort(const AValue: cardinal);
  1138. begin
  1139. if AValue<>0 then
  1140. Params.Values['Port']:=IntToStr(AValue)
  1141. else with params do if IndexOfName('Port') > -1 then
  1142. Delete(IndexOfName('Port'));
  1143. end;
  1144. function TSQLConnection.AttemptCommit(trans: TSQLHandle): boolean;
  1145. begin
  1146. try
  1147. Result:=Commit(trans);
  1148. except
  1149. if ForcedClose then
  1150. Result:=True
  1151. else
  1152. Raise;
  1153. end;
  1154. end;
  1155. function TSQLConnection.AttemptRollBack(trans: TSQLHandle): boolean;
  1156. begin
  1157. try
  1158. Result:=Rollback(trans);
  1159. except
  1160. if ForcedClose then
  1161. Result:=True
  1162. else
  1163. Raise;
  1164. end;
  1165. end;
  1166. procedure TSQLConnection.GetDBInfo(const ASchemaType : TSchemaType; const ASchemaObjectName, AReturnField : string; AList: TStrings);
  1167. var qry : TCustomSQLQuery;
  1168. begin
  1169. if not assigned(Transaction) then
  1170. DatabaseError(SErrConnTransactionnSet);
  1171. qry := TCustomSQLQuery.Create(nil);
  1172. try
  1173. qry.transaction := Transaction;
  1174. qry.database := Self;
  1175. with qry do
  1176. begin
  1177. ParseSQL := False;
  1178. SetSchemaInfo(ASchemaType,ASchemaObjectName,'');
  1179. open;
  1180. AList.Clear;
  1181. while not eof do
  1182. begin
  1183. AList.Append(trim(fieldbyname(AReturnField).asstring));
  1184. Next;
  1185. end;
  1186. end;
  1187. finally
  1188. qry.free;
  1189. end;
  1190. end;
  1191. function TSQLConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  1192. begin
  1193. Result := -1;
  1194. end;
  1195. procedure TSQLConnection.GetTableNames(List: TStrings; SystemTables: Boolean);
  1196. begin
  1197. if not SystemTables then
  1198. GetDBInfo(stTables,'','table_name',List)
  1199. else
  1200. GetDBInfo(stSysTables,'','table_name',List);
  1201. end;
  1202. procedure TSQLConnection.GetProcedureNames(List: TStrings);
  1203. begin
  1204. GetDBInfo(stProcedures,'','procedure_name',List);
  1205. end;
  1206. procedure TSQLConnection.GetFieldNames(const TableName: string; List: TStrings);
  1207. begin
  1208. GetDBInfo(stColumns,TableName,'column_name',List);
  1209. end;
  1210. procedure TSQLConnection.GetSchemaNames(List: TStrings);
  1211. begin
  1212. GetDBInfo(stSchemata,'','SCHEMA_NAME',List);
  1213. end;
  1214. procedure TSQLConnection.GetSequenceNames(List: TStrings);
  1215. begin
  1216. GetDBInfo(stSequences,'','SEQUENCE_NAME',List);
  1217. end;
  1218. {
  1219. See if we can integrate/merge this with GetDBInfo. They are virtually identical
  1220. }
  1221. Function TSQLConnection.GetObjectNames(ASchemaType: TSchemaType; AList : TSqlObjectIdentifierList) : Integer;
  1222. var
  1223. qry : TCustomSQLQuery;
  1224. vSchemaName, vObjectName: String;
  1225. f: TField;
  1226. begin
  1227. Result:=0;
  1228. if not assigned(Transaction) then
  1229. DatabaseError(SErrConnTransactionnSet);
  1230. qry := TCustomSQLQuery.Create(nil);
  1231. try
  1232. qry.transaction := Transaction;
  1233. qry.database := Self;
  1234. with qry do
  1235. begin
  1236. ParseSQL := False;
  1237. SetSchemaInfo(ASchemaType,TSchemaObjectNames[ASchemaType],'');
  1238. open;
  1239. f:=FindField(TSchemaObjectNames[stSchemata]);
  1240. while not eof do
  1241. begin
  1242. vSchemaName:='';
  1243. if Assigned(f) then
  1244. vSchemaName:=f.AsString;
  1245. vObjectName:=FieldByName(FSchemaObjectName).AsString;
  1246. AList.AddIdentifier(vObjectName, vSchemaName);
  1247. Next;
  1248. Inc(Result);
  1249. end;
  1250. end;
  1251. finally
  1252. qry.free;
  1253. end;
  1254. end;
  1255. function TSQLConnection.GetConnectionInfo(InfoType: TConnInfoType): string;
  1256. var i: TConnInfoType;
  1257. begin
  1258. Result:='';
  1259. if InfoType = citAll then
  1260. for i:=citServerType to citClientVersion do
  1261. begin
  1262. if Result<>'' then Result:=Result+',';
  1263. Result:=Result+'"'+GetConnectionInfo(i)+'"';
  1264. end;
  1265. end;
  1266. function TSQLConnection.GetStatementInfo(const ASQL: string): TSQLStatementInfo;
  1267. type TParsePart = (ppStart,ppWith,ppSelect,ppTableName,ppFrom,ppWhere,ppGroup,ppOrder,ppBogus);
  1268. TPhraseSeparator = (sepNone, sepWhiteSpace, sepComma, sepComment, sepParentheses, sepDoubleQuote, sepEnd);
  1269. TKeyword = (kwWITH, kwSELECT, kwINSERT, kwUPDATE, kwDELETE, kwFROM, kwJOIN, kwWHERE, kwGROUP, kwORDER, kwUNION, kwROWS, kwLIMIT, kwUnknown);
  1270. const
  1271. KeywordNames: array[TKeyword] of string =
  1272. ('WITH', 'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'FROM', 'JOIN', 'WHERE', 'GROUP', 'ORDER', 'UNION', 'ROWS', 'LIMIT', '');
  1273. var
  1274. PSQL, CurrentP, SavedP,
  1275. PhraseP, PStatementPart : pchar;
  1276. S : string;
  1277. ParsePart : TParsePart;
  1278. BracketCount : Integer;
  1279. Separator : TPhraseSeparator;
  1280. Keyword, K : TKeyword;
  1281. begin
  1282. PSQL:=Pchar(ASQL);
  1283. ParsePart := ppStart;
  1284. CurrentP := PSQL-1;
  1285. PhraseP := PSQL;
  1286. Result.TableName := '';
  1287. Result.Updateable := False;
  1288. Result.WhereStartPos := 0;
  1289. Result.WhereStopPos := 0;
  1290. repeat
  1291. begin
  1292. inc(CurrentP);
  1293. SavedP := CurrentP;
  1294. case CurrentP^ of
  1295. ' ', #9..#13:
  1296. Separator := sepWhiteSpace;
  1297. ',':
  1298. Separator := sepComma;
  1299. #0, ';':
  1300. Separator := sepEnd;
  1301. '(':
  1302. begin
  1303. Separator := sepParentheses;
  1304. // skip everything between brackets, since it could be a sub-select, and
  1305. // further nothing between brackets could be interesting for the parser.
  1306. BracketCount := 1;
  1307. repeat
  1308. inc(CurrentP);
  1309. if CurrentP^ = '(' then inc(BracketCount)
  1310. else if CurrentP^ = ')' then dec(BracketCount);
  1311. until (CurrentP^ = #0) or (BracketCount = 0);
  1312. if CurrentP^ <> #0 then inc(CurrentP);
  1313. end;
  1314. '"','`':
  1315. if SkipComments(CurrentP, sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions) then
  1316. Separator := sepDoubleQuote;
  1317. else
  1318. if SkipComments(CurrentP, sqEscapeSlash in ConnOptions, sqEscapeRepeat in ConnOptions) then
  1319. Separator := sepComment
  1320. else
  1321. Separator := sepNone;
  1322. end;
  1323. if (CurrentP > SavedP) and (SavedP > PhraseP) then
  1324. CurrentP := SavedP; // there is something before comment or left parenthesis
  1325. if Separator <> sepNone then
  1326. begin
  1327. if ((Separator in [sepWhitespace,sepComment]) and (PhraseP = SavedP)) then
  1328. PhraseP := CurrentP; // skip comments (but not parentheses) and white spaces
  1329. if (CurrentP-PhraseP > 0) or (Separator = sepEnd) then
  1330. begin
  1331. SetString(s, PhraseP, CurrentP-PhraseP);
  1332. Keyword := kwUnknown;
  1333. for K in TKeyword do
  1334. if SameText(s, KeywordNames[K]) then
  1335. begin
  1336. Keyword := K;
  1337. break;
  1338. end;
  1339. case ParsePart of
  1340. ppStart : begin
  1341. Result.StatementType := StrToStatementType(s);
  1342. case Keyword of
  1343. kwWITH : ParsePart := ppWith;
  1344. kwSELECT: ParsePart := ppSelect;
  1345. else break;
  1346. end;
  1347. end;
  1348. ppWith : begin
  1349. // WITH [RECURSIVE] CTE_name [ ( column_names ) ] AS ( CTE_query_definition ) [, ...]
  1350. // { SELECT | INSERT | UPDATE | DELETE } ...
  1351. case Keyword of
  1352. kwSELECT: Result.StatementType := stSelect;
  1353. kwINSERT: Result.StatementType := stInsert;
  1354. kwUPDATE: Result.StatementType := stUpdate;
  1355. kwDELETE: Result.StatementType := stDelete;
  1356. end;
  1357. if Result.StatementType <> stUnknown then break;
  1358. end;
  1359. ppSelect : begin
  1360. if Keyword = kwFROM then
  1361. ParsePart := ppTableName;
  1362. end;
  1363. ppTableName:
  1364. begin
  1365. // Meta-data requests are never updateable
  1366. // and select statements from more than one table
  1367. // and/or derived tables are also not updateable
  1368. if Separator in [sepWhitespace, sepComment, sepDoubleQuote, sepEnd] then
  1369. begin
  1370. Result.TableName := s;
  1371. Result.Updateable := True;
  1372. end;
  1373. ParsePart := ppFrom;
  1374. end;
  1375. ppFrom : begin
  1376. if (Keyword in [kwWHERE, kwGROUP, kwORDER, kwLIMIT, kwROWS]) or
  1377. (Separator = sepEnd) then
  1378. begin
  1379. case Keyword of
  1380. kwWHERE: ParsePart := ppWhere;
  1381. kwGROUP: ParsePart := ppGroup;
  1382. kwORDER: ParsePart := ppOrder;
  1383. else ParsePart := ppBogus;
  1384. end;
  1385. Result.WhereStartPos := PhraseP-PSQL+1;
  1386. PStatementPart := CurrentP;
  1387. end
  1388. else
  1389. // joined table or user_defined_function (...)
  1390. if (Keyword = kwJOIN) or (Separator in [sepComma, sepParentheses]) then
  1391. begin
  1392. Result.TableName := '';
  1393. Result.Updateable := False;
  1394. end;
  1395. end;
  1396. ppWhere : begin
  1397. if (Keyword in [kwGROUP, kwORDER, kwLIMIT, kwROWS]) or
  1398. (Separator = sepEnd) then
  1399. begin
  1400. ParsePart := ppBogus;
  1401. Result.WhereStartPos := PStatementPart-PSQL;
  1402. if (Separator = sepEnd) then
  1403. Result.WhereStopPos := CurrentP-PSQL+1
  1404. else
  1405. Result.WhereStopPos := PhraseP-PSQL+1;
  1406. end
  1407. else if (Keyword = kwUNION) then
  1408. begin
  1409. ParsePart := ppBogus;
  1410. Result.Updateable := False;
  1411. end;
  1412. end;
  1413. end; {case}
  1414. end;
  1415. if Separator in [sepComment, sepParentheses, sepDoubleQuote] then
  1416. dec(CurrentP);
  1417. PhraseP := CurrentP+1;
  1418. end
  1419. end;
  1420. until CurrentP^=#0;
  1421. end;
  1422. function TSQLConnection.GetAsSQLText(Field : TField) : string;
  1423. begin
  1424. if (not assigned(Field)) or Field.IsNull then Result := 'Null'
  1425. else case field.DataType of
  1426. ftString : Result := QuotedStr(Field.AsString);
  1427. ftDate : Result := '''' + FormatDateTime('yyyy-mm-dd',Field.AsDateTime,FSqlFormatSettings) + '''';
  1428. ftDateTime : Result := '''' + FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz',Field.AsDateTime,FSqlFormatSettings) + '''';
  1429. ftTime : Result := QuotedStr(TimeIntervalToString(Field.AsDateTime));
  1430. else
  1431. Result := Field.AsString;
  1432. end; {case}
  1433. end;
  1434. function TSQLConnection.GetAsSQLText(Param: TParam) : string;
  1435. begin
  1436. if (not assigned(Param)) or Param.IsNull then Result := 'Null'
  1437. else case Param.DataType of
  1438. ftGuid,
  1439. ftMemo,
  1440. ftFixedChar,
  1441. ftString : Result := QuotedStr(Param.AsString);
  1442. ftDate : Result := '''' + FormatDateTime('yyyy-mm-dd',Param.AsDateTime,FSQLFormatSettings) + '''';
  1443. ftTime : Result := QuotedStr(TimeIntervalToString(Param.AsDateTime));
  1444. ftDateTime : Result := '''' + FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Param.AsDateTime, FSQLFormatSettings) + '''';
  1445. ftCurrency,
  1446. ftBcd : Result := CurrToStr(Param.AsCurrency, FSQLFormatSettings);
  1447. ftFloat : Result := FloatToStr(Param.AsFloat, FSQLFormatSettings);
  1448. ftFMTBcd : Result := stringreplace(Param.AsString, DefaultFormatSettings.DecimalSeparator, FSQLFormatSettings.DecimalSeparator, []);
  1449. else
  1450. Result := Param.AsString;
  1451. end; {case}
  1452. end;
  1453. function TSQLConnection.GetHandle: pointer;
  1454. begin
  1455. Result := nil;
  1456. end;
  1457. function TSQLConnection.LogEvent(EventType: TDBEventType): Boolean;
  1458. begin
  1459. Result:=(Assigned(FOnLog) or Assigned(GlobalDBLogHook)) and (EventType in LogEvents);
  1460. end;
  1461. procedure TSQLConnection.LogParams(const AParams: TParams);
  1462. Var
  1463. S : String;
  1464. P : TParam;
  1465. begin
  1466. if not LogEvent(detParamValue) then
  1467. Exit;
  1468. For P in AParams do
  1469. begin
  1470. if P.IsNull then
  1471. S:='<NULL>'
  1472. else if (P.DataType in ftBlobTypes) and not (P.DataType in [ftMemo, ftFmtMemo,ftWideMemo]) then
  1473. S:='<BLOB>'
  1474. else
  1475. S:=P.AsString;
  1476. Log(detParamValue,Format(SLogParamValue,[P.Name,S]));
  1477. end;
  1478. end;
  1479. procedure TSQLConnection.Log(EventType: TDBEventType; const Msg: String);
  1480. Var
  1481. M : String;
  1482. begin
  1483. If LogEvent(EventType) then
  1484. begin
  1485. If Assigned(FonLog) then
  1486. FOnLog(Self,EventType,Msg);
  1487. If Assigned(GlobalDBLogHook) then
  1488. begin
  1489. If (Name<>'') then
  1490. M:=Name+' : '+Msg
  1491. else
  1492. M:=ClassName+' : '+Msg;
  1493. GlobalDBLogHook(Self,EventType,M);
  1494. end;
  1495. end;
  1496. end;
  1497. procedure TSQLConnection.RegisterStatement(S: TCustomSQLStatement);
  1498. begin
  1499. if FStatements.IndexOf(S)=-1 then
  1500. FStatements.Add(S);
  1501. end;
  1502. procedure TSQLConnection.UnRegisterStatement(S: TCustomSQLStatement);
  1503. begin
  1504. if Assigned(FStatements) then // Can be nil, when we are destroying and datasets are uncoupled.
  1505. FStatements.Remove(S);
  1506. end;
  1507. function TSQLConnection.InitialiseUpdateStatement(Query : TCustomSQLQuery; var qry : TCustomSQLQuery): TCustomSQLQuery;
  1508. begin
  1509. if not assigned(qry) then
  1510. begin
  1511. qry := TCustomSQLQuery.Create(nil);
  1512. qry.ParseSQL := False;
  1513. qry.DataBase := Self;
  1514. qry.Transaction := Query.SQLTransaction;
  1515. qry.Unidirectional:=True;
  1516. qry.UsePrimaryKeyAsKey:=False;
  1517. qry.PacketRecords:=1;
  1518. end;
  1519. Result:=qry;
  1520. end;
  1521. procedure TSQLConnection.AddFieldToUpdateWherePart(var sql_where : string;UpdateMode : TUpdateMode; F : TField);
  1522. begin
  1523. if (pfInKey in F.ProviderFlags)
  1524. or ((UpdateMode = upWhereAll) and (pfInWhere in F.ProviderFlags))
  1525. or ((UpdateMode = UpWhereChanged) and (pfInWhere in F.ProviderFlags) and (F.Value <> F.OldValue)) then
  1526. begin
  1527. if (sql_where<>'') then
  1528. sql_where:=sql_where + ' and ';
  1529. sql_where:= sql_where + '(' + FieldNameQuoteChars[0] + F.FieldName + FieldNameQuoteChars[1];
  1530. if F.OldValue = NULL then
  1531. sql_where := sql_where + ' is null '
  1532. else
  1533. sql_where := sql_where +'= :"' + 'OLD_' + F.FieldName + '"';
  1534. sql_where:=sql_where+') ';
  1535. end;
  1536. end;
  1537. function TSQLConnection.ConstructInsertSQL(Query: TCustomSQLQuery;
  1538. var ReturningClause: Boolean): string;
  1539. var x : integer;
  1540. sql_fields : string;
  1541. sql_values : string;
  1542. returning_fields : String;
  1543. F : TField;
  1544. begin
  1545. sql_fields := '';
  1546. sql_values := '';
  1547. returning_fields := '';
  1548. for x := 0 to Query.Fields.Count -1 do
  1549. begin
  1550. F:=Query.Fields[x];
  1551. if (not F.IsNull) and (pfInUpdate in F.ProviderFlags) and (not F.ReadOnly) then
  1552. begin
  1553. sql_fields := sql_fields + FieldNameQuoteChars[0] + F.FieldName + FieldNameQuoteChars[1] + ',';
  1554. sql_values := sql_values + ':"' + F.FieldName + '",';
  1555. end;
  1556. if ReturningClause and (pfRefreshOnInsert in F.ProviderFlags) then
  1557. returning_fields := returning_fields + FieldNameQuoteChars[0] + F.FieldName + FieldNameQuoteChars[1] + ',';
  1558. end;
  1559. if length(sql_fields) = 0 then
  1560. DatabaseErrorFmt(sNoUpdateFields,['insert'],self);
  1561. setlength(sql_fields,length(sql_fields)-1);
  1562. setlength(sql_values,length(sql_values)-1);
  1563. result := 'insert into ' + Query.FTableName + ' (' + sql_fields + ') values (' + sql_values + ')';
  1564. if ReturningClause then
  1565. begin
  1566. ReturningClause:=length(returning_fields) <> 0 ;
  1567. if ReturningClause then
  1568. begin
  1569. setlength(returning_fields,length(returning_fields)-1);
  1570. Result := Result + ' returning ' + returning_fields;
  1571. end;
  1572. end;
  1573. end;
  1574. function TSQLConnection.ConstructUpdateSQL(Query: TCustomSQLQuery;
  1575. var ReturningClause: Boolean): string;
  1576. var x : integer;
  1577. F : TField;
  1578. sql_set : string;
  1579. sql_where : string;
  1580. returning_fields : String;
  1581. begin
  1582. sql_set := '';
  1583. sql_where := '';
  1584. returning_fields := '';
  1585. for x := 0 to Query.Fields.Count -1 do
  1586. begin
  1587. F:=Query.Fields[x];
  1588. AddFieldToUpdateWherePart(sql_where,Query.UpdateMode,F);
  1589. if (pfInUpdate in F.ProviderFlags) and (not F.ReadOnly) then
  1590. sql_set := sql_set +FieldNameQuoteChars[0] + F.FieldName + FieldNameQuoteChars[1] +'=:"' + F.FieldName + '",';
  1591. if ReturningClause and (pfRefreshOnUpdate in F.ProviderFlags) then
  1592. returning_fields := returning_fields + FieldNameQuoteChars[0] + F.FieldName + FieldNameQuoteChars[1] + ',';
  1593. end;
  1594. if length(sql_set) = 0 then DatabaseErrorFmt(sNoUpdateFields,['update'],self);
  1595. setlength(sql_set,length(sql_set)-1);
  1596. if length(sql_where) = 0 then DatabaseErrorFmt(sNoWhereFields,['update'],self);
  1597. result := 'update ' + Query.FTableName + ' set ' + sql_set + ' where ' + sql_where;
  1598. if ReturningClause then
  1599. begin
  1600. ReturningClause:=length(returning_fields) <> 0 ;
  1601. if ReturningClause then
  1602. begin
  1603. setlength(returning_fields,length(returning_fields)-1);
  1604. Result := Result + ' returning ' + returning_fields;
  1605. end;
  1606. end;
  1607. end;
  1608. function TSQLConnection.ConstructDeleteSQL(Query : TCustomSQLQuery) : string;
  1609. var
  1610. x : integer;
  1611. sql_where : string;
  1612. begin
  1613. sql_where := '';
  1614. for x := 0 to Query.Fields.Count -1 do
  1615. AddFieldToUpdateWherePart(sql_where,Query.UpdateMode, Query.Fields[x]);
  1616. if length(sql_where) = 0 then
  1617. DatabaseErrorFmt(sNoWhereFields,['delete'],self);
  1618. result := 'delete from ' + Query.FTableName + ' where ' + sql_where;
  1619. end;
  1620. function TSQLConnection.ConstructRefreshSQL(Query: TCustomSQLQuery; UpdateKind: TUpdateKind): string;
  1621. Var
  1622. F : TField;
  1623. PF : TProviderFlag;
  1624. Where : String;
  1625. begin
  1626. Result:=Query.RefreshSQL.Text;
  1627. if (Result='') then
  1628. begin
  1629. Where:='';
  1630. PF:=RefreshFlags[UpdateKind];
  1631. For F in Query.Fields do
  1632. begin
  1633. if PF in F.ProviderFlags then
  1634. begin
  1635. if (Result<>'') then
  1636. Result:=Result+', ';
  1637. if (F.Origin<>'') and (F.Origin<>F.FieldName) then
  1638. Result:=Result+F.Origin+' AS '+F.FieldName
  1639. else
  1640. Result:=Result+FieldNameQuoteChars[0]+F.FieldName+FieldNameQuoteChars[1]
  1641. end;
  1642. if pfInkey in F.ProviderFlags then
  1643. begin
  1644. if (Where<>'') then
  1645. Where:=Where+' AND ';
  1646. Where:=Where+'('+FieldNameQuoteChars[0]+F.FieldName+FieldNameQuoteChars[1]+' = :'+F.FieldName+')';
  1647. end;
  1648. end;
  1649. if (Where='') then
  1650. DatabaseError(SErrNoKeyFieldForRefreshClause,Query);
  1651. Result:='SELECT '+Result+' FROM '+Query.FTableName+' WHERE '+Where;
  1652. end;
  1653. end;
  1654. procedure TSQLConnection.ApplyFieldUpdate(C : TSQLCursor; P : TSQLDBParam;F : TField; UseOldValue : Boolean);
  1655. begin
  1656. if UseOldValue then
  1657. P.AssignFieldValue(F,F.OldValue)
  1658. else
  1659. P.AssignFieldValue(F,F.Value);
  1660. P.FFieldDef:=F.FieldDef;
  1661. end;
  1662. procedure TSQLConnection.ApplyRecUpdate(Query: TCustomSQLQuery; UpdateKind: TUpdateKind);
  1663. var
  1664. qry : TCustomSQLQuery;
  1665. s : string;
  1666. x : integer;
  1667. Fld : TField;
  1668. P : TParam;
  1669. B,ReturningClause : Boolean;
  1670. begin
  1671. qry:=Nil;
  1672. ReturningClause:=(sqSupportReturning in ConnOptions) and not (sqoRefreshUsingSelect in Query.Options) and (Query.RefreshSQL.Count=0);
  1673. case UpdateKind of
  1674. ukInsert : begin
  1675. s := Trim(Query.FInsertSQL.Text);
  1676. if s = '' then
  1677. s := ConstructInsertSQL(Query, ReturningClause)
  1678. else
  1679. ReturningClause := False;
  1680. qry := InitialiseUpdateStatement(Query, Query.FInsertQry);
  1681. end;
  1682. ukModify : begin
  1683. s := Trim(Query.FUpdateSQL.Text);
  1684. if s = '' then begin
  1685. //if not assigned(Query.FUpdateQry) or (Query.UpdateMode<>upWhereKeyOnly) then // first time or dynamic where part
  1686. s := ConstructUpdateSQL(Query, ReturningClause);
  1687. end
  1688. else
  1689. ReturningClause := False;
  1690. qry := InitialiseUpdateStatement(Query, Query.FUpdateQry);
  1691. end;
  1692. ukDelete : begin
  1693. s := Trim(Query.FDeleteSQL.Text);
  1694. if (s='') and (not assigned(Query.FDeleteQry) or (Query.UpdateMode<>upWhereKeyOnly)) then
  1695. s := ConstructDeleteSQL(Query);
  1696. ReturningClause := False;
  1697. qry := InitialiseUpdateStatement(Query, Query.FDeleteQry);
  1698. end;
  1699. end;
  1700. if (s<>'') and (qry.SQL.Text<>s) then
  1701. qry.SQL.Text:=s; //assign only when changed, to avoid UnPrepare/Prepare
  1702. Assert(qry.SQL.Text<>'');
  1703. for x:=0 to Qry.Params.Count-1 do
  1704. begin
  1705. P:=Qry.Params[x];
  1706. S:=p.name;
  1707. B:=SameText(leftstr(S,4),'OLD_');
  1708. if B then
  1709. Delete(S,1,4);
  1710. Fld:=Query.FieldByName(S);
  1711. ApplyFieldUpdate(Query.Cursor,P as TSQLDBParam,Fld,B);
  1712. end;
  1713. if ReturningClause then
  1714. begin
  1715. Qry.Close;
  1716. Qry.Open
  1717. end
  1718. else
  1719. Qry.Execute;
  1720. if (scoApplyUpdatesChecksRowsAffected in Options) and (Qry.RowsAffected<>1) then
  1721. begin
  1722. Qry.Close;
  1723. DatabaseErrorFmt(SErrFailedToUpdateRecord, [Qry.RowsAffected], Query);
  1724. end;
  1725. if ReturningClause then
  1726. Query.ApplyReturningResult(Qry,UpdateKind);
  1727. end;
  1728. function TSQLConnection.RefreshLastInsertID(Query: TCustomSQLQuery; Field: TField): Boolean;
  1729. begin
  1730. Result:=False;
  1731. end;
  1732. procedure TSQLConnection.FreeFldBuffers(cursor: TSQLCursor);
  1733. begin
  1734. // empty
  1735. end;
  1736. function TSQLConnection.StartImplicitTransaction(trans: TSQLHandle; aParams: string): boolean;
  1737. begin
  1738. Result:=False;
  1739. end;
  1740. function TSQLConnection.GetSchemaInfoSQL( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string;
  1741. begin
  1742. case SchemaType of
  1743. stProcedures: Result := 'SELECT *, ROUTINE_NAME AS PROCEDURE_NAME FROM INFORMATION_SCHEMA.ROUTINES';
  1744. stSchemata : Result := 'SELECT * FROM INFORMATION_SCHEMA.SCHEMATA';
  1745. stSequences : Result := 'SELECT * FROM INFORMATION_SCHEMA.SEQUENCES';
  1746. else DatabaseError(SMetadataUnavailable);
  1747. end;
  1748. end;
  1749. function TSQLConnection.GetNextValueSQL(const SequenceName: string; IncrementBy: Integer): string;
  1750. begin
  1751. Result := 'SELECT NEXT VALUE FOR ' + SequenceName;
  1752. end;
  1753. function TSQLConnection.GetNextValue(const SequenceName: string; IncrementBy: integer): Int64;
  1754. var
  1755. Q: TCustomSQLQuery;
  1756. begin
  1757. Result := 0;
  1758. Q := TCustomSQLQuery.Create(nil);
  1759. try
  1760. Q.DataBase := Self;
  1761. Q.Transaction := Transaction;
  1762. Q.SQL.Text := GetNextValueSQL(SequenceName, IncrementBy);
  1763. Q.Open;
  1764. if not Q.Eof then
  1765. Result := Q.Fields[0].AsLargeInt;
  1766. Q.Close;
  1767. finally
  1768. FreeAndNil(Q);
  1769. end;
  1770. end;
  1771. procedure TSQLConnection.MaybeConnect;
  1772. begin
  1773. If Not Connected then
  1774. begin
  1775. If (scoExplicitConnect in Options) then
  1776. DatabaseErrorFmt(SErrImplicitConnect,[Name]);
  1777. Connected:=True;
  1778. end;
  1779. end;
  1780. procedure TSQLConnection.CreateDB;
  1781. begin
  1782. DatabaseError(SNotSupported);
  1783. end;
  1784. procedure TSQLConnection.DropDB;
  1785. begin
  1786. DatabaseError(SNotSupported);
  1787. end;
  1788. { TSQLTransaction }
  1789. constructor TSQLTransaction.Create(AOwner : TComponent);
  1790. begin
  1791. inherited Create(AOwner);
  1792. FParams := TStringList.Create;
  1793. Action := caRollBack;
  1794. end;
  1795. destructor TSQLTransaction.Destroy;
  1796. begin
  1797. EndTransaction;
  1798. FreeAndNil(FTrans);
  1799. FreeAndNil(FParams);
  1800. inherited Destroy;
  1801. end;
  1802. procedure TSQLTransaction.EndTransaction;
  1803. begin
  1804. Case Action of
  1805. caCommit, caCommitRetaining :
  1806. Commit;
  1807. caNone,
  1808. caRollback, caRollbackRetaining :
  1809. if not (stoUseImplicit in Options) then
  1810. RollBack
  1811. else
  1812. CloseTrans;
  1813. end;
  1814. end;
  1815. procedure TSQLTransaction.SetParams(const AValue: TStringList);
  1816. begin
  1817. FParams.Assign(AValue);
  1818. end;
  1819. function TSQLTransaction.GetSQLConnection: TSQLConnection;
  1820. begin
  1821. Result:=Database as TSQLConnection;
  1822. end;
  1823. procedure TSQLTransaction.SetOptions(AValue: TSQLTransactionOptions);
  1824. begin
  1825. if FOptions=AValue then Exit;
  1826. if (stoUseImplicit in Avalue) and Assigned(SQLConnection) And Not (sqImplicitTransaction in SQLConnection.ConnOptions) then
  1827. DatabaseErrorFmt(SErrNoImplicitTransaction, [SQLConnection.ClassName]);
  1828. FOptions:=AValue;
  1829. end;
  1830. procedure TSQLTransaction.SetSQLConnection(AValue: TSQLConnection);
  1831. begin
  1832. Database:=AValue;
  1833. end;
  1834. Procedure TSQLTransaction.MaybeStartTransaction;
  1835. begin
  1836. if not Active then
  1837. begin
  1838. if (stoExplicitStart in Options) then
  1839. DatabaseErrorFmt(SErrImplictTransactionStart, [Database.Name,Name]);
  1840. StartTransaction;
  1841. end;
  1842. end;
  1843. function TSQLTransaction.GetHandle: Pointer;
  1844. begin
  1845. Result := SQLConnection.GetTransactionHandle(FTrans);
  1846. end;
  1847. Function TSQLTransaction.AllowClose(DS: TDBDataset): Boolean;
  1848. begin
  1849. if (DS is TSQLQuery) then
  1850. Result:=not (sqoKeepOpenOnCommit in TSQLQuery(DS).Options)
  1851. else
  1852. Result:=Inherited AllowClose(DS);
  1853. end;
  1854. procedure TSQLTransaction.Commit;
  1855. begin
  1856. if Active then
  1857. begin
  1858. CloseDataSets;
  1859. If LogEvent(detCommit) then
  1860. Log(detCommit,SCommitting);
  1861. if (stoUseImplicit in Options) or SQLConnection.AttemptCommit(FTrans) then
  1862. begin
  1863. CloseTrans;
  1864. FreeAndNil(FTrans);
  1865. end;
  1866. end;
  1867. end;
  1868. procedure TSQLTransaction.CommitRetaining;
  1869. begin
  1870. if Active then
  1871. begin
  1872. If LogEvent(detCommit) then
  1873. Log(detCommit,SCommitRetaining);
  1874. SQLConnection.CommitRetaining(FTrans);
  1875. end;
  1876. end;
  1877. procedure TSQLTransaction.Rollback;
  1878. begin
  1879. if Active then
  1880. begin
  1881. if (stoUseImplicit in Options) then
  1882. DatabaseError(SErrImplicitNoRollBack);
  1883. CloseDataSets;
  1884. If LogEvent(detRollback) then
  1885. Log(detRollback,SRollingBack);
  1886. if SQLConnection.AttemptRollBack(FTrans) then
  1887. begin
  1888. CloseTrans;
  1889. FreeAndNil(FTrans);
  1890. end;
  1891. end;
  1892. end;
  1893. procedure TSQLTransaction.RollbackRetaining;
  1894. begin
  1895. if Active then
  1896. begin
  1897. if (stoUseImplicit in Options) then
  1898. DatabaseError(SErrImplicitNoRollBack);
  1899. If LogEvent(detRollback) then
  1900. Log(detRollback,SRollBackRetaining);
  1901. SQLConnection.RollBackRetaining(FTrans);
  1902. end;
  1903. end;
  1904. procedure TSQLTransaction.StartTransaction;
  1905. var db : TSQLConnection;
  1906. begin
  1907. if Active then
  1908. DatabaseError(SErrTransAlreadyActive);
  1909. db := SQLConnection;
  1910. if Db = nil then
  1911. DatabaseError(SErrDatabasenAssigned);
  1912. Db.MaybeConnect;
  1913. if not assigned(FTrans) then FTrans := Db.AllocateTransactionHandle;
  1914. if (stoUseImplicit in Options) then
  1915. begin
  1916. if Db.StartImplicitTransaction(FTrans,FParams.CommaText) then
  1917. OpenTrans
  1918. end
  1919. else
  1920. begin
  1921. if Db.StartDBTransaction(FTrans,FParams.CommaText) then
  1922. OpenTrans
  1923. end;
  1924. end;
  1925. Procedure TSQLTransaction.SetDatabase(Value: TDatabase);
  1926. begin
  1927. If Value<>Database then
  1928. begin
  1929. if Assigned(Value) and not (Value is TSQLConnection) then
  1930. DatabaseErrorFmt(SErrNotASQLConnection, [Value.Name], Self);
  1931. CheckInactive;
  1932. if (stoUseImplicit in Options) and Assigned(Value) and Not (sqImplicitTransaction in TSQLConnection(Value).ConnOptions) then
  1933. DatabaseErrorFmt(SErrNoImplicitTransaction, [Value.ClassName]);
  1934. If Assigned(Database) then
  1935. if SQLConnection.Transaction = Self then SQLConnection.Transaction := nil;
  1936. inherited;
  1937. If Assigned(Database) and not (csLoading in ComponentState) then
  1938. If SQLConnection.Transaction = Nil then SQLConnection.Transaction := Self;
  1939. end;
  1940. end;
  1941. Function TSQLTransaction.LogEvent(EventType: TDBEventType): Boolean;
  1942. begin
  1943. Result:=Assigned(Database) and SQLConnection.LogEvent(EventType);
  1944. end;
  1945. Procedure TSQLTransaction.Log(EventType: TDBEventType; Const Msg: String);
  1946. Var
  1947. M : String;
  1948. begin
  1949. If LogEvent(EventType) then
  1950. begin
  1951. If (Name<>'') then
  1952. M:=Name+' : '+Msg
  1953. else
  1954. M:=Msg;
  1955. SQLConnection.Log(EventType,M);
  1956. end;
  1957. end;
  1958. { TSQLSequence }
  1959. constructor TSQLSequence.Create(AQuery: TCustomSQLQuery);
  1960. begin
  1961. inherited Create;
  1962. FQuery := AQuery;
  1963. FApplyEvent := saeOnNewRecord;
  1964. FIncrementBy := 1;
  1965. end;
  1966. procedure TSQLSequence.Assign(Source: TPersistent);
  1967. var SourceSequence: TSQLSequence;
  1968. begin
  1969. if Source is TSQLSequence then
  1970. begin
  1971. SourceSequence := TSQLSequence(Source);
  1972. FFieldName := SourceSequence.FieldName;
  1973. FSequenceName := SourceSequence.SequenceName;
  1974. FIncrementBy := SourceSequence.IncrementBy;
  1975. FApplyEvent := SourceSequence.ApplyEvent;
  1976. end
  1977. else
  1978. inherited;
  1979. end;
  1980. procedure TSQLSequence.Apply;
  1981. var Field: TField;
  1982. begin
  1983. if Assigned(FQuery) and (FSequenceName<>'') and (FFieldName<>'') then
  1984. begin
  1985. Field := FQuery.FindField(FFieldName);
  1986. if Assigned(Field) and Field.IsNull then
  1987. Field.AsLargeInt := GetNextValue;
  1988. end;
  1989. end;
  1990. function TSQLSequence.GetNextValue: Int64;
  1991. begin
  1992. if (FQuery=Nil) or (FQuery.SQLConnection=Nil) then
  1993. DatabaseError(SErrDatabasenAssigned);
  1994. Result := FQuery.SQLConnection.GetNextValue(FSequenceName, FIncrementBy);
  1995. end;
  1996. Type
  1997. { TQuerySQLStatement }
  1998. TQuerySQLStatement = Class(TCustomSQLStatement)
  1999. protected
  2000. FQuery : TCustomSQLQuery;
  2001. Function CreateDataLink : TDataLink; override;
  2002. Function GetSchemaType : TSchemaType; override;
  2003. Function GetSchemaObjectName : String; override;
  2004. Function GetSchemaPattern: String; override;
  2005. procedure GetStatementInfo(var ASQL: String; out Info: TSQLStatementInfo); override;
  2006. procedure OnChangeSQL(Sender : TObject); override;
  2007. end;
  2008. { TQuerySQLStatement }
  2009. function TQuerySQLStatement.CreateDataLink: TDataLink;
  2010. begin
  2011. Result:=TMasterParamsDataLink.Create(FQuery);
  2012. end;
  2013. function TQuerySQLStatement.GetSchemaType: TSchemaType;
  2014. begin
  2015. if Assigned(FQuery) then
  2016. Result:=FQuery.FSchemaType
  2017. else
  2018. Result:=stNoSchema;
  2019. end;
  2020. function TQuerySQLStatement.GetSchemaObjectName: String;
  2021. begin
  2022. if Assigned(FQuery) then
  2023. Result:=FQuery.FSchemaObjectname
  2024. else
  2025. Result:=inherited GetSchemaObjectName;
  2026. end;
  2027. function TQuerySQLStatement.GetSchemaPattern: String;
  2028. begin
  2029. if Assigned(FQuery) then
  2030. Result:=FQuery.FSchemaPattern
  2031. else
  2032. Result:=inherited GetSchemaPattern;
  2033. end;
  2034. procedure TQuerySQLStatement.GetStatementInfo(var ASQL: String; out Info: TSQLStatementInfo);
  2035. begin
  2036. inherited GetStatementInfo(ASQL, Info);
  2037. If Assigned(FQuery) then
  2038. // Note: practical side effect of switch off ParseSQL is that UpdateServerIndexDefs is bypassed
  2039. // which is used as performance tuning option
  2040. if (FQuery.FSchemaType = stNoSchema) and FParseSQL then
  2041. begin
  2042. FQuery.FUpdateable:=Info.Updateable;
  2043. FQuery.FTableName:=Info.TableName;
  2044. FQuery.FWhereStartPos:=Info.WhereStartPos;
  2045. FQuery.FWhereStopPos:=Info.WhereStopPos;
  2046. if FQuery.ServerFiltered then
  2047. ASQL:=FQuery.AddFilter(ASQL);
  2048. end
  2049. else
  2050. begin
  2051. FQuery.FUpdateable:=false;
  2052. FQuery.FTableName:='';
  2053. FQuery.FWhereStartPos:=0;
  2054. FQuery.FWhereStopPos:=0;
  2055. end;
  2056. end;
  2057. procedure TQuerySQLStatement.OnChangeSQL(Sender: TObject);
  2058. begin
  2059. UnPrepare;
  2060. inherited OnChangeSQL(Sender);
  2061. If ParamCheck and Assigned(FDataLink) then
  2062. (FDataLink as TMasterParamsDataLink).RefreshParamNames;
  2063. FQuery.ServerIndexDefs.Updated:=false;
  2064. end;
  2065. { TCustomSQLQuery }
  2066. constructor TCustomSQLQuery.Create(AOwner : TComponent);
  2067. Var
  2068. F : TQuerySQLStatement;
  2069. begin
  2070. inherited Create(AOwner);
  2071. F:=TQuerySQLStatement.Create(Self);
  2072. F.FQuery:=Self;
  2073. FStatement:=F;
  2074. FInsertSQL := TStringList.Create;
  2075. FInsertSQL.OnChange := @OnChangeModifySQL;
  2076. FUpdateSQL := TStringList.Create;
  2077. FUpdateSQL.OnChange := @OnChangeModifySQL;
  2078. FDeleteSQL := TStringList.Create;
  2079. FDeleteSQL.OnChange := @OnChangeModifySQL;
  2080. FRefreshSQL := TStringList.Create;
  2081. FRefreshSQL.OnChange := @OnChangeModifySQL;
  2082. FSequence := TSQLSequence.Create(Self);
  2083. FServerIndexDefs := TServerIndexDefs.Create(Self);
  2084. FServerFiltered := False;
  2085. FServerFilterText := '';
  2086. FSchemaType:=stNoSchema;
  2087. FSchemaObjectName:='';
  2088. FSchemaPattern:='';
  2089. // Delphi has upWhereAll as default, but since strings and oldvalue's don't work yet
  2090. // (variants) set it to upWhereKeyOnly
  2091. FUpdateMode := upWhereKeyOnly;
  2092. FUsePrimaryKeyAsKey := True;
  2093. end;
  2094. destructor TCustomSQLQuery.Destroy;
  2095. begin
  2096. if Active then Close;
  2097. UnPrepare;
  2098. FreeAndNil(FStatement);
  2099. FreeAndNil(FInsertSQL);
  2100. FreeAndNil(FUpdateSQL);
  2101. FreeAndNil(FDeleteSQL);
  2102. FreeAndNil(FRefreshSQL);
  2103. FreeAndNil(FSequence);
  2104. FreeAndNil(FServerIndexDefs);
  2105. inherited Destroy;
  2106. end;
  2107. function TCustomSQLQuery.ParamByName(const AParamName: String): TParam;
  2108. begin
  2109. Result:=Params.ParamByName(AParamName);
  2110. end;
  2111. procedure TCustomSQLQuery.OnChangeModifySQL(Sender : TObject);
  2112. begin
  2113. CheckInactive;
  2114. end;
  2115. procedure TCustomSQLQuery.SetDatabase(Value : TDatabase);
  2116. var DB : TSQLConnection;
  2117. begin
  2118. if Database = Value then Exit;
  2119. if Assigned(Value) and not (Value is TSQLConnection) then
  2120. DatabaseErrorFmt(SErrNotASQLConnection, [Value.Name], Self);
  2121. UnPrepare;
  2122. DB := TSQLConnection(Value);
  2123. If Assigned(FStatement) then
  2124. FStatement.Database := DB;
  2125. inherited;
  2126. if Assigned(DB) and Assigned(DB.Transaction) and (not Assigned(Transaction) or (Transaction.DataBase<>Database)) then
  2127. Transaction := DB.Transaction;
  2128. end;
  2129. procedure TCustomSQLQuery.SetTransaction(Value: TDBTransaction);
  2130. begin
  2131. if Transaction = Value then Exit;
  2132. UnPrepare;
  2133. inherited;
  2134. If Assigned(FStatement) then
  2135. FStatement.Transaction := TSQLTransaction(Value);
  2136. If Assigned(Transaction) and Assigned(Transaction.DataBase) and (Database<>Transaction.DataBase) then
  2137. Database := Transaction.Database;
  2138. end;
  2139. function TCustomSQLQuery.IsPrepared: Boolean;
  2140. begin
  2141. if Assigned(Fstatement) then
  2142. Result := FStatement.Prepared
  2143. else
  2144. Result := False;
  2145. end;
  2146. function TCustomSQLQuery.AddFilter(SQLstr: string): string;
  2147. begin
  2148. if (FWhereStartPos > 0) and (FWhereStopPos > 0) then
  2149. begin
  2150. system.insert('(',SQLstr,FWhereStartPos+1);
  2151. system.insert(')',SQLstr,FWhereStopPos+1);
  2152. end;
  2153. if FWhereStartPos = 0 then
  2154. SQLstr := SQLstr + ' where (' + ServerFilter + ')'
  2155. else if FWhereStopPos > 0 then
  2156. system.insert(' and ('+ServerFilter+') ',SQLstr,FWhereStopPos+2)
  2157. else
  2158. system.insert(' where ('+ServerFilter+') ',SQLstr,FWhereStartPos);
  2159. Result := SQLstr;
  2160. end;
  2161. function TCustomSQLQuery.NeedRefreshRecord(UpdateKind: TUpdateKind): Boolean;
  2162. Var
  2163. PF : TProviderFlag;
  2164. I : Integer;
  2165. DoReturning : Boolean;
  2166. begin
  2167. Result:=(FRefreshSQL.Count<>0);
  2168. DoReturning:=(sqSupportReturning in SQLConnection.ConnOptions) and not (sqoRefreshUsingSelect in Options);
  2169. if Not (Result or DoReturning) then
  2170. begin
  2171. PF:=RefreshFlags[UpdateKind];
  2172. I:=0;
  2173. While (Not Result) and (I<Fields.Count) do
  2174. begin
  2175. Result:=PF in Fields[i].ProviderFlags;
  2176. Inc(I);
  2177. end;
  2178. end;
  2179. end;
  2180. function TCustomSQLQuery.RefreshRecord(UpdateKind: TUpdateKind): Boolean;
  2181. Var
  2182. Q : TCustomSQLQuery;
  2183. P : TParam;
  2184. F,FD : TField;
  2185. N : String;
  2186. begin
  2187. Result:=False;
  2188. Q:=TCustomSQLQuery.Create(Nil);
  2189. try
  2190. Q.Database:=Self.Database;
  2191. Q.Transaction:=Self.Transaction;
  2192. Q.SQL.Text:=SQLConnection.ConstructRefreshSQL(Self,UpdateKind);
  2193. For P in Q.Params do
  2194. begin
  2195. N:=P.Name;
  2196. If CompareText(Copy(N,1,4),'OLD_')=0 then
  2197. system.Delete(N,1,4);
  2198. F:=Fields.FindField(N);
  2199. if Assigned(F) then
  2200. P.AssignField(F);
  2201. end;
  2202. Q.Open;
  2203. try
  2204. if (Q.EOF and Q.BOF) then
  2205. DatabaseError(SErrRefreshEmptyResult,Self)
  2206. else
  2207. begin
  2208. if Q.RecordCount<>1 then
  2209. DatabaseErrorFmt(SErrRefreshNotSingleton,[Q.RecordCount],Self);
  2210. For F in Q.Fields do
  2211. begin
  2212. FD:=Fields.FindField(F.FieldName);
  2213. if Assigned(FD) then
  2214. begin
  2215. FD.Assign(F);
  2216. Result:=True; // We could check if the new value differs from the old, but we won't.
  2217. end;
  2218. end;
  2219. end
  2220. finally
  2221. Q.Close;
  2222. end;
  2223. finally
  2224. Q.Free;
  2225. end;
  2226. end;
  2227. procedure TCustomSQLQuery.ApplyReturningResult(Q: TCustomSQLQuery; UpdateKind : TUpdateKind);
  2228. Var
  2229. S : TDataSetState;
  2230. refreshFlag : TProviderFlag;
  2231. F : TField;
  2232. begin
  2233. RefreshFlag:=RefreshFlags[UpdateKind];
  2234. S:=SetTempState(dsRefreshFields);
  2235. try
  2236. For F in Fields do
  2237. if RefreshFlag in F.ProviderFlags then
  2238. F.Assign(Q.FieldByName(F.FieldName));
  2239. finally
  2240. RestoreState(S);
  2241. end;
  2242. end;
  2243. procedure TCustomSQLQuery.ApplyFilter;
  2244. begin
  2245. FreeFldBuffers;
  2246. FStatement.Unprepare;
  2247. FIsEOF := False;
  2248. inherited InternalClose;
  2249. FStatement.DoPrepare;
  2250. FStatement.DoExecute;
  2251. inherited InternalOpen;
  2252. First;
  2253. end;
  2254. procedure TCustomSQLQuery.SetActive(Value: Boolean);
  2255. begin
  2256. inherited SetActive(Value);
  2257. // The query is UnPrepared, so that if a transaction closes all datasets
  2258. // they also get unprepared
  2259. if not Value and IsPrepared then UnPrepare;
  2260. end;
  2261. procedure TCustomSQLQuery.SetServerFiltered(Value: Boolean);
  2262. begin
  2263. if Value and not ParseSQL then
  2264. DatabaseErrorFmt(SNoParseSQL,['Filtering ']);
  2265. if (ServerFiltered <> Value) then
  2266. begin
  2267. FServerFiltered := Value;
  2268. if Active then ApplyFilter;
  2269. end;
  2270. end;
  2271. procedure TCustomSQLQuery.SetServerFilterText(const Value: string);
  2272. begin
  2273. if Value <> ServerFilter then
  2274. begin
  2275. FServerFilterText := Value;
  2276. if Active then ApplyFilter;
  2277. end;
  2278. end;
  2279. procedure TCustomSQLQuery.Prepare;
  2280. begin
  2281. FStatement.Prepare;
  2282. if Assigned(FStatement.FCursor) then
  2283. with FStatement.FCursor do
  2284. FInitFieldDef := FSelectable;
  2285. end;
  2286. procedure TCustomSQLQuery.UnPrepare;
  2287. begin
  2288. CheckInactive;
  2289. If Assigned(FStatement) then
  2290. FStatement.Unprepare;
  2291. end;
  2292. procedure TCustomSQLQuery.FreeFldBuffers;
  2293. begin
  2294. if assigned(Cursor) then
  2295. SQLConnection.FreeFldBuffers(Cursor);
  2296. end;
  2297. function TCustomSQLQuery.GetParamCheck: Boolean;
  2298. begin
  2299. Result:=FStatement.ParamCheck;
  2300. end;
  2301. function TCustomSQLQuery.GetParams: TParams;
  2302. begin
  2303. Result:=FStatement.Params;
  2304. end;
  2305. function TCustomSQLQuery.GetParseSQL: Boolean;
  2306. begin
  2307. Result:=FStatement.ParseSQL;
  2308. end;
  2309. function TCustomSQLQuery.GetServerIndexDefs: TServerIndexDefs;
  2310. begin
  2311. Result := FServerIndexDefs;
  2312. end;
  2313. function TCustomSQLQuery.GetSQL: TStringList;
  2314. begin
  2315. Result:=TStringList(Fstatement.SQL);
  2316. end;
  2317. function TCustomSQLQuery.GetSQLConnection: TSQLConnection;
  2318. begin
  2319. Result:=Database as TSQLConnection;
  2320. end;
  2321. function TCustomSQLQuery.GetSQLTransaction: TSQLTransaction;
  2322. begin
  2323. Result:=Transaction as TSQLTransaction;
  2324. end;
  2325. function TCustomSQLQuery.Cursor: TSQLCursor;
  2326. begin
  2327. Result:=FStatement.Cursor;
  2328. end;
  2329. function TCustomSQLQuery.Fetch : boolean;
  2330. begin
  2331. if Not Assigned(Cursor) then
  2332. Exit;
  2333. if not Cursor.FSelectable then
  2334. Exit;
  2335. If LogEvent(detFetch) then
  2336. Log(detFetch,FStatement.FServerSQL);
  2337. if not FIsEof then FIsEOF := not SQLConnection.Fetch(Cursor);
  2338. Result := not FIsEOF;
  2339. end;
  2340. procedure TCustomSQLQuery.Execute;
  2341. begin
  2342. FStatement.Execute;
  2343. end;
  2344. function TCustomSQLQuery.RowsAffected: TRowsCount;
  2345. begin
  2346. Result:=FStatement.RowsAffected;
  2347. end;
  2348. function TCustomSQLQuery.LoadField(FieldDef : TFieldDef;buffer : pointer; out CreateBlob : boolean) : boolean;
  2349. begin
  2350. result := SQLConnection.LoadField(Cursor,FieldDef,buffer, Createblob)
  2351. end;
  2352. procedure TCustomSQLQuery.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  2353. ABlobBuf: PBufBlobField);
  2354. begin
  2355. SQLConnection.LoadBlobIntoBuffer(FieldDef, ABlobBuf, Cursor,SQLTransaction);
  2356. end;
  2357. procedure TCustomSQLQuery.InternalAddRecord(Buffer: Pointer; AAppend: Boolean);
  2358. begin
  2359. // not implemented - sql dataset
  2360. end;
  2361. procedure TCustomSQLQuery.InternalClose;
  2362. begin
  2363. if assigned(Cursor) then
  2364. begin
  2365. if Cursor.FSelectable then
  2366. FreeFldBuffers;
  2367. // Some SQLConnections does not support statement [un]preparation,
  2368. // so let them do cleanup f.e. cancel pending queries and/or free resultset
  2369. if not Prepared then FStatement.DoUnprepare;
  2370. end;
  2371. if DefaultFields then
  2372. DestroyFields;
  2373. FIsEOF := False;
  2374. if assigned(FUpdateQry) then FreeAndNil(FUpdateQry);
  2375. if assigned(FInsertQry) then FreeAndNil(FInsertQry);
  2376. if assigned(FDeleteQry) then FreeAndNil(FDeleteQry);
  2377. // FRecordSize := 0;
  2378. inherited InternalClose;
  2379. end;
  2380. procedure TCustomSQLQuery.InternalInitFieldDefs;
  2381. begin
  2382. if FLoadingFieldDefs then
  2383. Exit;
  2384. FLoadingFieldDefs := True;
  2385. try
  2386. FieldDefs.Clear;
  2387. Prepare;
  2388. SQLConnection.AddFieldDefs(Cursor,FieldDefs);
  2389. finally
  2390. FLoadingFieldDefs := False;
  2391. if assigned(Cursor) then Cursor.FInitFieldDef := False;
  2392. end;
  2393. end;
  2394. procedure TCustomSQLQuery.InternalOpen;
  2395. var counter, fieldc : integer;
  2396. F : TField;
  2397. IndexFields : TStrings;
  2398. begin
  2399. if IsReadFromPacket then
  2400. begin
  2401. // When we read from file there is no need for Cursor, also note that Database may not be assigned
  2402. //FStatement.AllocateCursor;
  2403. //Cursor.FSelectable:=True;
  2404. //Cursor.FStatementType:=stSelect;
  2405. FUpdateable:=True;
  2406. end
  2407. else
  2408. begin
  2409. Prepare;
  2410. if not Cursor.FSelectable then
  2411. DatabaseError(SErrNoSelectStatement,Self);
  2412. // Call UpdateServerIndexDefs before Execute, to avoid problems with connections
  2413. // which do not allow processing multiple recordsets at a time. (Microsoft
  2414. // calls this MARS, see bug 13241)
  2415. if DefaultFields and FUpdateable and FusePrimaryKeyAsKey and (not IsUniDirectional) then
  2416. UpdateServerIndexDefs;
  2417. Execute;
  2418. if not Cursor.FSelectable then
  2419. DatabaseError(SErrNoSelectStatement,Self);
  2420. // InternalInitFieldDef is only called after a prepare. i.e. not twice if
  2421. // a dataset is opened - closed - opened.
  2422. if Cursor.FInitFieldDef then InternalInitFieldDefs;
  2423. if DefaultFields then
  2424. begin
  2425. CreateFields;
  2426. if FUpdateable and FusePrimaryKeyAsKey and (not IsUniDirectional) then
  2427. for counter := 0 to ServerIndexDefs.Count-1 do
  2428. if ixPrimary in ServerIndexDefs[counter].Options then
  2429. begin
  2430. IndexFields := TStringList.Create;
  2431. ExtractStrings([';'],[' '],pchar(ServerIndexDefs[counter].Fields),IndexFields);
  2432. for fieldc := 0 to IndexFields.Count-1 do
  2433. begin
  2434. F := FindField(IndexFields[fieldc]);
  2435. if F <> nil then
  2436. F.ProviderFlags := F.ProviderFlags + [pfInKey];
  2437. end;
  2438. IndexFields.Free;
  2439. end;
  2440. end;
  2441. end;
  2442. BindFields(True);
  2443. if not ReadOnly and not FUpdateable and (FSchemaType=stNoSchema) then
  2444. begin
  2445. if (trim(FDeleteSQL.Text) <> '') or (trim(FUpdateSQL.Text) <> '') or
  2446. (trim(FInsertSQL.Text) <> '') then FUpdateable := True;
  2447. end;
  2448. inherited InternalOpen;
  2449. end;
  2450. procedure TCustomSQLQuery.InternalRefresh;
  2451. begin
  2452. if (ChangeCount>0) and (sqoCancelUpdatesOnRefresh in Options) then
  2453. CancelUpdates;
  2454. inherited InternalRefresh;
  2455. end;
  2456. // public part
  2457. procedure TCustomSQLQuery.ExecSQL;
  2458. begin
  2459. try
  2460. Prepare;
  2461. Execute;
  2462. If sqoAutoCommit in Options then
  2463. begin
  2464. // Retrieve rows affected
  2465. FStatement.RowsAffected;
  2466. SQLTransaction.Commit;
  2467. end;
  2468. finally
  2469. // Cursor has to be assigned, or else the prepare went wrong before PrepareStatment was
  2470. // called, so UnPrepareStatement shoudn't be called either
  2471. // Don't deallocate cursor; f.e. RowsAffected is requested later
  2472. if not Prepared and (assigned(Database)) and (assigned(Cursor)) then SQLConnection.UnPrepareStatement(Cursor);
  2473. end;
  2474. end;
  2475. procedure TCustomSQLQuery.ApplyUpdates(MaxErrors: Integer);
  2476. begin
  2477. inherited ApplyUpdates(MaxErrors);
  2478. If sqoAutoCommit in Options then
  2479. begin
  2480. // Retrieve rows affected for last update.
  2481. FStatement.RowsAffected;
  2482. SQLTransaction.Commit;
  2483. end;
  2484. end;
  2485. procedure TCustomSQLQuery.Post;
  2486. begin
  2487. inherited Post;
  2488. If (sqoAutoApplyUpdates in Options) then
  2489. ApplyUpdates;
  2490. end;
  2491. procedure TCustomSQLQuery.Delete;
  2492. begin
  2493. inherited Delete;
  2494. If (sqoAutoApplyUpdates in Options) then
  2495. ApplyUpdates;
  2496. end;
  2497. procedure TCustomSQLQuery.SetReadOnly(AValue : Boolean);
  2498. begin
  2499. CheckInactive;
  2500. inherited SetReadOnly(AValue);
  2501. end;
  2502. procedure TCustomSQLQuery.SetParseSQL(AValue : Boolean);
  2503. begin
  2504. CheckInactive;
  2505. FStatement.ParseSQL:=AValue;
  2506. if not AValue then
  2507. FServerFiltered := False;
  2508. end;
  2509. procedure TCustomSQLQuery.SetSQL(const AValue: TStringList);
  2510. begin
  2511. FStatement.SQL.Assign(AValue);
  2512. end;
  2513. procedure TCustomSQLQuery.SetUsePrimaryKeyAsKey(AValue : Boolean);
  2514. begin
  2515. if not Active then FusePrimaryKeyAsKey := AValue
  2516. else
  2517. begin
  2518. // Just temporary, this should be possible in the future
  2519. DatabaseError(SActiveDataset);
  2520. end;
  2521. end;
  2522. procedure TCustomSQLQuery.UpdateServerIndexDefs;
  2523. begin
  2524. FServerIndexDefs.Clear;
  2525. if assigned(DataBase) and (FTableName<>'') then
  2526. SQLConnection.UpdateIndexDefs(ServerIndexDefs,FTableName);
  2527. end;
  2528. function TCustomSQLQuery.NeedLastInsertID: TField;
  2529. Var
  2530. I : Integer;
  2531. begin
  2532. Result:=Nil;
  2533. if sqLastInsertID in SQLConnection.ConnOptions then
  2534. begin
  2535. I:=0;
  2536. While (Result=Nil) and (I<Fields.Count) do
  2537. begin
  2538. Result:=Fields[i];
  2539. if (Result.DataType<>ftAutoInc) or not Result.IsNull then
  2540. Result:=Nil;
  2541. Inc(I);
  2542. end;
  2543. end
  2544. end;
  2545. function TCustomSQLQuery.RefreshLastInsertID(Field: TField): Boolean;
  2546. begin
  2547. Result:=SQLConnection.RefreshLastInsertID(Self, Field);
  2548. end;
  2549. procedure TCustomSQLQuery.ApplyRecUpdate(UpdateKind: TUpdateKind);
  2550. Var
  2551. DoRefresh : Boolean;
  2552. LastIDField : TField;
  2553. S : TDataSetState;
  2554. begin
  2555. // Moved to connection: the SQLConnection always has more information about types etc.
  2556. // than SQLQuery itself.
  2557. SQLConnection.ApplyRecUpdate(Self,UpdateKind);
  2558. if UpdateKind=ukInsert then
  2559. LastIDField:=NeedLastInsertID
  2560. else
  2561. LastIDField:=nil;
  2562. DoRefresh:=(UpdateKind in [ukModify,ukInsert]) and NeedRefreshRecord(UpdateKind);
  2563. if assigned(LastIDField) or DoRefresh then
  2564. begin
  2565. // updates fields directly in record buffer of TBufDataSet
  2566. // TDataSet buffers are resynchronized at end of ApplyUpdates process
  2567. S:=SetTempState(dsRefreshFields);
  2568. try
  2569. if assigned(LastIDField) then
  2570. RefreshLastInsertID(LastIDField);
  2571. if DoRefresh then
  2572. RefreshRecord(UpdateKind);
  2573. finally
  2574. RestoreState(S);
  2575. end;
  2576. end;
  2577. end;
  2578. procedure TCustomSQLQuery.SetPacketRecords(aValue: integer);
  2579. begin
  2580. if (AValue=PacketRecords) then exit;
  2581. if (AValue<>-1) and (sqoKeepOpenOnCommit in Options) then
  2582. DatabaseError(SErrDisconnectedPacketRecords);
  2583. Inherited SetPacketRecords(aValue);
  2584. end;
  2585. function TCustomSQLQuery.GetCanModify: Boolean;
  2586. begin
  2587. // the test for assigned(Cursor) is needed for the case that the dataset isn't opened
  2588. if assigned(Cursor) and (Cursor.FStatementType = stSelect) then
  2589. Result:= FUpdateable and (not ReadOnly) and (not IsUniDirectional)
  2590. else
  2591. Result := False;
  2592. end;
  2593. procedure TCustomSQLQuery.SetUpdateMode(AValue : TUpdateMode);
  2594. begin
  2595. FUpdateMode := AValue;
  2596. end;
  2597. procedure TCustomSQLQuery.SetSchemaInfo( ASchemaType : TSchemaType; ASchemaObjectName, ASchemaPattern : string);
  2598. begin
  2599. FSchemaType:=ASchemaType;
  2600. FSchemaObjectName:=ASchemaObjectName;
  2601. FSchemaPattern:=ASchemaPattern;
  2602. end;
  2603. procedure TCustomSQLQuery.BeforeRefreshOpenCursor;
  2604. begin
  2605. // This is only necessary because TIBConnection can not re-open a
  2606. // prepared cursor. In fact this is wrong, but has never led to
  2607. // problems because in SetActive(false) queries are always
  2608. // unprepared. (which is also wrong, but has to be fixed later)
  2609. if IsPrepared then with SQLConnection do
  2610. UnPrepareStatement(Cursor);
  2611. end;
  2612. function TCustomSQLQuery.LogEvent(EventType: TDBEventType): Boolean;
  2613. begin
  2614. Result:=Assigned(Database) and SQLConnection.LogEvent(EventType);
  2615. end;
  2616. procedure TCustomSQLQuery.Log(EventType: TDBEventType; const Msg: String);
  2617. Var
  2618. M : String;
  2619. begin
  2620. If LogEvent(EventType) then
  2621. begin
  2622. M:=Msg;
  2623. If (Name<>'') then
  2624. M:=Name+' : '+M;
  2625. SQLConnection.Log(EventType,M);
  2626. end;
  2627. end;
  2628. class function TCustomSQLQuery.FieldDefsClass: TFieldDefsClass;
  2629. begin
  2630. Result:=TSQLDBFieldDefs;
  2631. end;
  2632. function TCustomSQLQuery.GetStatementType : TStatementType;
  2633. begin
  2634. if Assigned(Cursor) then
  2635. Result:=Cursor.FStatementType
  2636. else
  2637. Result:=stUnknown;
  2638. end;
  2639. procedure TCustomSQLQuery.SetParamCheck(AValue: Boolean);
  2640. begin
  2641. FStatement.ParamCheck:=AValue;
  2642. end;
  2643. procedure TCustomSQLQuery.SetOptions(AValue: TSQLQueryOptions);
  2644. begin
  2645. if FOptions=AValue then Exit;
  2646. CheckInactive;
  2647. FOptions:=AValue;
  2648. if sqoKeepOpenOnCommit in FOptions then
  2649. PacketRecords:=-1;
  2650. end;
  2651. procedure TCustomSQLQuery.SetSQLConnection(AValue: TSQLConnection);
  2652. begin
  2653. Database:=AValue;
  2654. end;
  2655. procedure TCustomSQLQuery.SetSQLTransaction(AValue: TSQLTransaction);
  2656. begin
  2657. Transaction:=AValue;
  2658. end;
  2659. procedure TCustomSQLQuery.SetInsertSQL(const AValue: TStringList);
  2660. begin
  2661. FInsertSQL.Assign(AValue);
  2662. end;
  2663. procedure TCustomSQLQuery.SetUpdateSQL(const AValue: TStringList);
  2664. begin
  2665. FUpdateSQL.Assign(AValue);
  2666. end;
  2667. procedure TCustomSQLQuery.SetDeleteSQL(const AValue: TStringList);
  2668. begin
  2669. FDeleteSQL.Assign(AValue);
  2670. end;
  2671. procedure TCustomSQLQuery.SetRefreshSQL(const AValue: TStringList);
  2672. begin
  2673. FRefreshSQL.Assign(AValue);
  2674. end;
  2675. procedure TCustomSQLQuery.SetParams(AValue: TParams);
  2676. begin
  2677. FStatement.Params.Assign(AValue);
  2678. end;
  2679. procedure TCustomSQLQuery.SetDataSource(AValue: TDataSource);
  2680. Var
  2681. DS : TDataSource;
  2682. begin
  2683. DS:=DataSource;
  2684. If (AValue<>DS) then
  2685. begin
  2686. If Assigned(AValue) and (AValue.Dataset=Self) then
  2687. DatabaseError(SErrCircularDataSourceReferenceNotAllowed,Self);
  2688. If Assigned(DS) then
  2689. DS.RemoveFreeNotification(Self);
  2690. FStatement.DataSource:=AValue;
  2691. end;
  2692. end;
  2693. function TCustomSQLQuery.GetDataSource: TDataSource;
  2694. begin
  2695. If Assigned(FStatement) then
  2696. Result:=FStatement.DataSource
  2697. else
  2698. Result:=Nil;
  2699. end;
  2700. procedure TCustomSQLQuery.Notification(AComponent: TComponent; Operation: TOperation);
  2701. begin
  2702. Inherited;
  2703. If (Operation=opRemove) and (AComponent=DataSource) then
  2704. DataSource:=Nil;
  2705. end;
  2706. procedure TCustomSQLQuery.DoOnNewRecord;
  2707. begin
  2708. inherited;
  2709. if FSequence.ApplyEvent = saeOnNewRecord then
  2710. FSequence.Apply;
  2711. end;
  2712. procedure TCustomSQLQuery.DoBeforePost;
  2713. begin
  2714. if (State = dsInsert) and (FSequence.ApplyEvent = saeOnPost) then
  2715. FSequence.Apply;
  2716. inherited;
  2717. end;
  2718. function TCustomSQLQuery.PSGetUpdateException(E: Exception; Prev: EUpdateError): EUpdateError;
  2719. var
  2720. PrevErrorCode, ErrorCode: Integer;
  2721. begin
  2722. if Assigned(Prev) then
  2723. PrevErrorCode := Prev.ErrorCode
  2724. else
  2725. PrevErrorCode := 0;
  2726. if E is ESQLDatabaseError then
  2727. ErrorCode := ESQLDatabaseError(E).ErrorCode
  2728. else
  2729. ErrorCode := 0;
  2730. Result := EUpdateError.Create(SOnUpdateError, E.Message, ErrorCode, PrevErrorCode, E);
  2731. end;
  2732. function TCustomSQLQuery.PSGetTableName: string;
  2733. begin
  2734. Result := FTableName;
  2735. end;
  2736. { TSQLScript }
  2737. procedure TSQLScript.ExecuteStatement(SQLStatement: TStrings;
  2738. var StopExecution: Boolean);
  2739. begin
  2740. fquery.SQL.assign(SQLStatement);
  2741. fquery.ExecSQL;
  2742. end;
  2743. procedure TSQLScript.ExecuteDirective(Directive, Argument: String;
  2744. var StopExecution: Boolean);
  2745. begin
  2746. if assigned (FOnDirective) then
  2747. FOnDirective (Self, Directive, Argument, StopExecution);
  2748. end;
  2749. procedure TSQLScript.ExecuteCommit(CommitRetaining: boolean=true);
  2750. begin
  2751. if FTransaction is TSQLTransaction then
  2752. if CommitRetaining then
  2753. TSQLTransaction(FTransaction).CommitRetaining
  2754. else
  2755. begin
  2756. TSQLTransaction(FTransaction).Commit;
  2757. TSQLTransaction(FTransaction).StartTransaction;
  2758. end
  2759. else
  2760. begin
  2761. FTransaction.Active := false;
  2762. FTransaction.Active := true;
  2763. end;
  2764. end;
  2765. procedure TSQLScript.SetDatabase(Value: TDatabase);
  2766. begin
  2767. FDatabase := Value;
  2768. end;
  2769. procedure TSQLScript.SetTransaction(Value: TDBTransaction);
  2770. begin
  2771. FTransaction := Value;
  2772. end;
  2773. procedure TSQLScript.CheckDatabase;
  2774. begin
  2775. If (FDatabase=Nil) then
  2776. DatabaseError(SErrNoDatabaseAvailable,Self)
  2777. end;
  2778. constructor TSQLScript.Create(AOwner: TComponent);
  2779. begin
  2780. inherited Create(AOwner);
  2781. FQuery := TCustomSQLQuery.Create(nil);
  2782. FQuery.ParamCheck := false; // Do not parse for parameters; breaks use of e.g. select bla into :bla in Firebird procedures
  2783. end;
  2784. destructor TSQLScript.Destroy;
  2785. begin
  2786. FQuery.Free;
  2787. inherited Destroy;
  2788. end;
  2789. procedure TSQLScript.Execute;
  2790. begin
  2791. FQuery.DataBase := FDatabase;
  2792. FQuery.Transaction := FTransaction;
  2793. inherited Execute;
  2794. end;
  2795. procedure TSQLScript.ExecuteScript;
  2796. begin
  2797. Execute;
  2798. end;
  2799. { Connection definitions }
  2800. Var
  2801. ConnDefs : TStringList;
  2802. Procedure CheckDefs;
  2803. begin
  2804. If (ConnDefs=Nil) then
  2805. begin
  2806. ConnDefs:=TStringList.Create;
  2807. ConnDefs.Sorted:=True;
  2808. ConnDefs.Duplicates:=dupError;
  2809. end;
  2810. end;
  2811. Procedure DoneDefs;
  2812. Var
  2813. I : Integer;
  2814. begin
  2815. If Assigned(ConnDefs) then
  2816. begin
  2817. For I:=ConnDefs.Count-1 downto 0 do
  2818. begin
  2819. ConnDefs.Objects[i].Free;
  2820. ConnDefs.Delete(I);
  2821. end;
  2822. FreeAndNil(ConnDefs);
  2823. end;
  2824. end;
  2825. Function GetConnectionDef(ConnectorName : String) : TConnectionDef;
  2826. Var
  2827. I : Integer;
  2828. begin
  2829. CheckDefs;
  2830. I:=ConnDefs.IndexOf(ConnectorName);
  2831. If (I<>-1) then
  2832. Result:=TConnectionDef(ConnDefs.Objects[i])
  2833. else
  2834. Result:=Nil;
  2835. end;
  2836. procedure RegisterConnection(Def: TConnectionDefClass);
  2837. Var
  2838. I : Integer;
  2839. begin
  2840. CheckDefs;
  2841. I:=ConnDefs.IndexOf(Def.TypeName);
  2842. If (I=-1) then
  2843. ConnDefs.AddObject(Def.TypeName,Def.Create)
  2844. else
  2845. begin
  2846. ConnDefs.Objects[I].Free;
  2847. ConnDefs.Objects[I]:=Def.Create;
  2848. end;
  2849. end;
  2850. procedure UnRegisterConnection(Def: TConnectionDefClass);
  2851. begin
  2852. UnRegisterConnection(Def.TypeName);
  2853. end;
  2854. procedure UnRegisterConnection(ConnectionName: String);
  2855. Var
  2856. I : Integer;
  2857. begin
  2858. if (ConnDefs<>Nil) then
  2859. begin
  2860. I:=ConnDefs.IndexOf(ConnectionName);
  2861. If (I<>-1) then
  2862. begin
  2863. ConnDefs.Objects[I].Free;
  2864. ConnDefs.Delete(I);
  2865. end;
  2866. end;
  2867. end;
  2868. procedure GetConnectionList(List: TSTrings);
  2869. begin
  2870. CheckDefs;
  2871. List.Text:=ConnDefs.Text;
  2872. end;
  2873. { TSQLConnector }
  2874. procedure TSQLConnector.SetConnectorType(const AValue: String);
  2875. begin
  2876. if FConnectorType<>AValue then
  2877. begin
  2878. CheckDisconnected;
  2879. If Assigned(FProxy) then
  2880. FreeProxy;
  2881. FConnectorType:=AValue;
  2882. CreateProxy;
  2883. end;
  2884. end;
  2885. procedure TSQLConnector.SetTransaction(Value: TSQLTransaction);
  2886. begin
  2887. inherited SetTransaction(Value);
  2888. If Assigned(FProxy) and (FProxy.Transaction<>Value) then
  2889. FProxy.FTransaction:=Value;
  2890. end;
  2891. procedure TSQLConnector.DoInternalConnect;
  2892. Var
  2893. D : TConnectionDef;
  2894. begin
  2895. inherited DoInternalConnect;
  2896. CheckProxy;
  2897. FProxy.CharSet:=Self.CharSet;
  2898. FProxy.DatabaseName:=Self.DatabaseName;
  2899. FProxy.HostName:=Self.HostName;
  2900. FProxy.LogEvents:=Self.LogEvents;
  2901. FProxy.Password:=Self.Password;
  2902. FProxy.Role:=Self.Role;
  2903. FProxy.UserName:=Self.UserName;
  2904. FProxy.FTransaction:=Self.Transaction;
  2905. FProxy.LogEvents:=Self.LogEvents;
  2906. FProxy.OnLog:=Self.OnLog;
  2907. FProxy.Options:=Self.Options;
  2908. D:=GetConnectionDef(ConnectorType);
  2909. D.ApplyParams(Params,FProxy);
  2910. FProxy.Connected:=True;
  2911. end;
  2912. procedure TSQLConnector.DoInternalDisconnect;
  2913. begin
  2914. FProxy.Connected:=False;
  2915. inherited DoInternalDisconnect;
  2916. end;
  2917. procedure TSQLConnector.CheckProxy;
  2918. begin
  2919. If (FProxy=Nil) then
  2920. CreateProxy;
  2921. end;
  2922. procedure TSQLConnector.CreateProxy;
  2923. Var
  2924. D : TConnectionDef;
  2925. begin
  2926. D:=GetConnectionDef(ConnectorType);
  2927. If (D=Nil) then
  2928. DatabaseErrorFmt(SErrUnknownConnectorType,[ConnectorType],Self);
  2929. FProxy:=D.ConnectionClass.Create(Self);
  2930. FFieldNameQuoteChars := FProxy.FieldNameQuoteChars;
  2931. FConnOptions := FProxy.ConnOptions;
  2932. end;
  2933. procedure TSQLConnector.FreeProxy;
  2934. begin
  2935. FProxy.Connected:=False;
  2936. FreeAndNil(FProxy);
  2937. end;
  2938. function TSQLConnector.StrToStatementType(s: string): TStatementType;
  2939. begin
  2940. CheckProxy;
  2941. Result:=FProxy.StrToStatementType(s);
  2942. end;
  2943. function TSQLConnector.GetAsSQLText(Field: TField): string;
  2944. begin
  2945. CheckProxy;
  2946. Result:=FProxy.GetAsSQLText(Field);
  2947. end;
  2948. function TSQLConnector.GetAsSQLText(Param: TParam): string;
  2949. begin
  2950. CheckProxy;
  2951. Result:=FProxy.GetAsSQLText(Param);
  2952. end;
  2953. function TSQLConnector.GetHandle: pointer;
  2954. begin
  2955. CheckProxy;
  2956. Result:=FProxy.GetHandle;
  2957. end;
  2958. function TSQLConnector.AllocateCursorHandle: TSQLCursor;
  2959. begin
  2960. CheckProxy;
  2961. Result:=FProxy.AllocateCursorHandle;
  2962. end;
  2963. procedure TSQLConnector.DeAllocateCursorHandle(var cursor: TSQLCursor);
  2964. begin
  2965. CheckProxy;
  2966. FProxy.DeAllocateCursorHandle(cursor);
  2967. end;
  2968. function TSQLConnector.AllocateTransactionHandle: TSQLHandle;
  2969. begin
  2970. CheckProxy;
  2971. Result:=FProxy.AllocateTransactionHandle;
  2972. end;
  2973. procedure TSQLConnector.PrepareStatement(cursor: TSQLCursor;
  2974. ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  2975. begin
  2976. CheckProxy;
  2977. FProxy.PrepareStatement(cursor, ATransaction, buf, AParams);
  2978. end;
  2979. procedure TSQLConnector.Execute(cursor: TSQLCursor;
  2980. atransaction: tSQLtransaction; AParams: TParams);
  2981. begin
  2982. CheckProxy;
  2983. FProxy.Execute(cursor, atransaction, AParams);
  2984. end;
  2985. function TSQLConnector.Fetch(cursor: TSQLCursor): boolean;
  2986. begin
  2987. CheckProxy;
  2988. Result:=FProxy.Fetch(cursor);
  2989. end;
  2990. procedure TSQLConnector.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TfieldDefs
  2991. );
  2992. begin
  2993. CheckProxy;
  2994. FProxy.AddFieldDefs(cursor, FieldDefs);
  2995. end;
  2996. procedure TSQLConnector.UnPrepareStatement(cursor: TSQLCursor);
  2997. begin
  2998. CheckProxy;
  2999. FProxy.UnPrepareStatement(cursor);
  3000. end;
  3001. procedure TSQLConnector.FreeFldBuffers(cursor: TSQLCursor);
  3002. begin
  3003. CheckProxy;
  3004. FProxy.FreeFldBuffers(cursor);
  3005. end;
  3006. function TSQLConnector.LoadField(cursor: TSQLCursor; FieldDef: TfieldDef;
  3007. buffer: pointer; out CreateBlob: boolean): boolean;
  3008. begin
  3009. CheckProxy;
  3010. Result:=FProxy.LoadField(cursor, FieldDef, buffer, CreateBlob);
  3011. end;
  3012. procedure TSQLConnector.LoadBlobIntoBuffer(FieldDef: TFieldDef;
  3013. ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  3014. begin
  3015. CheckProxy;
  3016. FProxy.LoadBlobIntoBuffer(FieldDef, ABlobBuf, cursor, ATransaction);
  3017. end;
  3018. function TSQLConnector.RowsAffected(cursor: TSQLCursor): TRowsCount;
  3019. begin
  3020. CheckProxy;
  3021. Result := FProxy.RowsAffected(cursor);
  3022. end;
  3023. function TSQLConnector.GetTransactionHandle(trans: TSQLHandle): pointer;
  3024. begin
  3025. CheckProxy;
  3026. Result:=FProxy.GetTransactionHandle(trans);
  3027. end;
  3028. function TSQLConnector.Commit(trans: TSQLHandle): boolean;
  3029. begin
  3030. CheckProxy;
  3031. Result:=FProxy.Commit(trans);
  3032. end;
  3033. function TSQLConnector.RollBack(trans: TSQLHandle): boolean;
  3034. begin
  3035. CheckProxy;
  3036. Result:=FProxy.RollBack(trans);
  3037. end;
  3038. function TSQLConnector.StartDBTransaction(trans: TSQLHandle; aParams: string): boolean;
  3039. begin
  3040. CheckProxy;
  3041. Result:=FProxy.StartDBTransaction(trans, aParams);
  3042. end;
  3043. procedure TSQLConnector.CommitRetaining(trans: TSQLHandle);
  3044. begin
  3045. CheckProxy;
  3046. FProxy.CommitRetaining(trans);
  3047. end;
  3048. procedure TSQLConnector.RollBackRetaining(trans: TSQLHandle);
  3049. begin
  3050. CheckProxy;
  3051. FProxy.RollBackRetaining(trans);
  3052. end;
  3053. procedure TSQLConnector.UpdateIndexDefs(IndexDefs: TIndexDefs;
  3054. TableName: string);
  3055. begin
  3056. CheckProxy;
  3057. FProxy.UpdateIndexDefs(IndexDefs, TableName);
  3058. end;
  3059. function TSQLConnector.GetSchemaInfoSQL(SchemaType: TSchemaType;
  3060. SchemaObjectName, SchemaPattern: string): string;
  3061. begin
  3062. CheckProxy;
  3063. Result:=FProxy.GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaPattern);
  3064. end;
  3065. { TConnectionDef }
  3066. class function TConnectionDef.TypeName: String;
  3067. begin
  3068. Result:='';
  3069. end;
  3070. class function TConnectionDef.ConnectionClass: TSQLConnectionClass;
  3071. begin
  3072. Result:=Nil;
  3073. end;
  3074. class function TConnectionDef.Description: String;
  3075. begin
  3076. Result:='';
  3077. end;
  3078. class function TConnectionDef.DefaultLibraryName: String;
  3079. begin
  3080. Result:='';
  3081. end;
  3082. class function TConnectionDef.LoadFunction: TLibraryLoadFunction;
  3083. begin
  3084. Result:=Nil;
  3085. end;
  3086. class function TConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  3087. begin
  3088. Result:=Nil;
  3089. end;
  3090. class function TConnectionDef.LoadedLibraryName: string;
  3091. begin
  3092. Result:='';
  3093. end;
  3094. procedure TConnectionDef.ApplyParams(Params: TStrings;
  3095. AConnection: TSQLConnection);
  3096. begin
  3097. AConnection.Params.Assign(Params);
  3098. end;
  3099. { TServerIndexDefs }
  3100. constructor TServerIndexDefs.create(ADataset: TDataset);
  3101. begin
  3102. if not (ADataset is TCustomSQLQuery) then
  3103. DatabaseErrorFmt(SErrNotASQLQuery,[ADataset.Name]);
  3104. inherited create(ADataset);
  3105. end;
  3106. procedure TServerIndexDefs.Update;
  3107. begin
  3108. if (not updated) and assigned(Dataset) then
  3109. begin
  3110. TCustomSQLQuery(Dataset).UpdateServerIndexDefs;
  3111. updated := True;
  3112. end;
  3113. end;
  3114. Initialization
  3115. Finalization
  3116. DoneDefs;
  3117. end.