sqldb.pp 82 KB

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