oracleconnection.pp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. unit oracleconnection;
  2. {
  3. Copyright (c) 2006-2014 by Joost van der Sluis, FPC contributors
  4. Oracle RDBMS connector using the OCI protocol
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. **********************************************************************}
  8. {$mode objfpc}{$H+}
  9. {$Define LinkDynamically}
  10. interface
  11. uses
  12. Classes, SysUtils, db, dbconst, sqldb, bufdataset,
  13. {$IfDef LinkDynamically}
  14. ocidyn,
  15. {$ELSE}
  16. oci,
  17. {$ENDIF}
  18. oratypes;
  19. const
  20. DefaultTimeOut = 60;
  21. type
  22. EOraDatabaseError = class(ESQLDatabaseError)
  23. public
  24. property ORAErrorCode: integer read ErrorCode; deprecated 'Please use ErrorCode instead of ORAErrorCode'; // June 2014
  25. end;
  26. TOracleTrans = Class(TSQLHandle)
  27. protected
  28. FOciSvcCtx : POCISvcCtx;
  29. FOciTrans : POCITrans;
  30. FOciFlags : ub4;
  31. public
  32. destructor Destroy(); override;
  33. end;
  34. TOraFieldBuf = record
  35. DescType : ub4; // descriptor type
  36. Buffer : pointer;
  37. Ind : sb2; // indicator
  38. Len : ub4;
  39. Size : ub4;
  40. end;
  41. TOracleCursor = Class(TSQLCursor)
  42. protected
  43. FOciStmt : POCIStmt;
  44. FieldBuffers : array of TOraFieldBuf;
  45. ParamBuffers : array of TOraFieldBuf;
  46. end;
  47. { TOracleConnection }
  48. TOracleConnection = class (TSQLConnection)
  49. private
  50. FOciEnvironment : POciEnv;
  51. FOciError : POCIError;
  52. FOciServer : POCIServer;
  53. FOciUserSession : POCISession;
  54. FUserMem : pointer;
  55. procedure HandleError;
  56. procedure GetParameters(cursor : TSQLCursor; AParams : TParams);
  57. procedure SetParameters(cursor : TSQLCursor; AParams : TParams);
  58. protected
  59. // - Connect/disconnect
  60. procedure DoInternalConnect; override;
  61. procedure DoInternalDisconnect; override;
  62. // - Handle (de)allocation
  63. function AllocateCursorHandle:TSQLCursor; override;
  64. procedure DeAllocateCursorHandle(var cursor:TSQLCursor); override;
  65. function AllocateTransactionHandle:TSQLHandle; override;
  66. // - Statement handling
  67. procedure PrepareStatement(cursor:TSQLCursor; ATransaction:TSQLTransaction; buf:string; AParams:TParams); override;
  68. procedure UnPrepareStatement(cursor:TSQLCursor); override;
  69. // - Transaction handling
  70. procedure InternalStartDBTransaction(trans:TOracleTrans);
  71. function GetTransactionHandle(trans:TSQLHandle):pointer; override;
  72. function StartDBTransaction(trans:TSQLHandle; AParams:string):boolean; override;
  73. function Commit(trans:TSQLHandle):boolean; override;
  74. function Rollback(trans:TSQLHandle):boolean; override;
  75. procedure CommitRetaining(trans:TSQLHandle); override;
  76. procedure RollbackRetaining(trans:TSQLHandle); override;
  77. // - Statement execution
  78. procedure Execute(cursor:TSQLCursor; ATransaction:TSQLTransaction; AParams:TParams); override;
  79. function RowsAffected(cursor: TSQLCursor): TRowsCount; override;
  80. // - Result retrieval
  81. procedure AddFieldDefs(cursor:TSQLCursor; FieldDefs:TFieldDefs); override;
  82. function Fetch(cursor:TSQLCursor):boolean; override;
  83. function LoadField(cursor:TSQLCursor; FieldDef:TFieldDef; buffer:pointer; out CreateBlob : boolean):boolean; override;
  84. procedure LoadBlobIntoBuffer(FieldDef: TFieldDef; ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction); override;
  85. procedure FreeFldBuffers(cursor:TSQLCursor); override;
  86. procedure UpdateIndexDefs(IndexDefs : TIndexDefs;TableName : string); override;
  87. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; override;
  88. public
  89. constructor Create(AOwner : TComponent); override;
  90. end;
  91. { TOracleConnectionDef }
  92. TOracleConnectionDef = Class(TConnectionDef)
  93. Class Function TypeName : String; override;
  94. Class Function ConnectionClass : TSQLConnectionClass; override;
  95. Class Function Description : String; override;
  96. Class Function DefaultLibraryName : String; override;
  97. Class Function LoadFunction : TLibraryLoadFunction; override;
  98. Class Function UnLoadFunction : TLibraryUnLoadFunction; override;
  99. Class Function LoadedLibraryName: string; override;
  100. end;
  101. implementation
  102. uses
  103. math, StrUtils, FmtBCD;
  104. const
  105. ObjectQuote='"'; //beginning and ending quote for objects such as table names. Note: can be different from quotes around field names
  106. ResourceString
  107. SErrEnvCreateFailed = 'The creation of an Oracle environment failed.';
  108. SErrHandleAllocFailed = 'The allocation of the error handle failed.';
  109. SErrOracle = 'Oracle returned error %s:';
  110. type
  111. TODateTime = record
  112. year : sb2;
  113. month : ub1;
  114. day : ub1;
  115. hour : ub1;
  116. min : ub1;
  117. sec : ub1;
  118. fsec : ub4;
  119. end;
  120. // Callback functions
  121. function cbf_no_data(ictxp:Pdvoid; bindp:POCIBind; iter:ub4; index:ub4; bufpp:PPdvoid;
  122. alenp:Pub4; piecep:Pub1; indp:PPdvoid):sb4;cdecl;
  123. begin
  124. bufpp^ := nil;
  125. alenp^ := 0;
  126. indp^ := nil;
  127. piecep^ := OCI_ONE_PIECE;
  128. result:=OCI_CONTINUE;
  129. end;
  130. function cbf_get_data(octxp:Pdvoid; bindp:POCIBind; iter:ub4; index:ub4; bufpp:PPdvoid;
  131. alenp:PPub4; piecep:Pub1; indp:PPdvoid; rcodep:PPub2):sb4;cdecl;
  132. begin
  133. // Only 1 row can be stored. No support for multiple rows: only the last row is kept.
  134. bufpp^:=TOraFieldBuf(octxp^).Buffer;
  135. indp^ := @TOraFieldBuf(octxp^).Ind;
  136. TOraFieldBuf(octxp^).Len:=TOraFieldBuf(octxp^).Size; //reset size to full buffer
  137. alenp^ := @TOraFieldBuf(octxp^).Len;
  138. rcodep^:=nil;
  139. piecep^ := OCI_ONE_PIECE;
  140. result:=OCI_CONTINUE;
  141. end;
  142. // Conversions
  143. Procedure FmtBCD2Nvu(bcd:tBCD;b:pByte);
  144. var
  145. i,j,cnt : integer;
  146. nibbles : array [0..maxfmtbcdfractionsize-1] of byte;
  147. exp : shortint;
  148. bb : byte;
  149. begin
  150. fillchar(b[0],22,#0);
  151. if BCDPrecision(bcd)=0 then // zero, special case
  152. begin
  153. b[0]:=1;
  154. b[1]:=$80;
  155. end
  156. else
  157. begin
  158. if (BCDPrecision(bcd)-BCDScale(bcd)) mod 2 <>0 then // odd number before decimal point
  159. begin
  160. nibbles[0]:=0;
  161. j:=1;
  162. end
  163. else
  164. j:=0;
  165. for i:=0 to bcd.Precision -1 do
  166. if i mod 2 =0 then
  167. nibbles[i+j]:=bcd.Fraction[i div 2] shr 4
  168. else
  169. nibbles[i+j]:=bcd.Fraction[i div 2] and $0f;
  170. nibbles[bcd.Precision+j]:=0; // make sure last nibble is also 0 in case we have odd scale
  171. exp:=(BCDPrecision(bcd)-BCDScale(bcd)+1) div 2;
  172. cnt:=exp+(BCDScale(bcd)+1) div 2;
  173. // to avoid "ora 01438: value larger than specified precision allowed for this column"
  174. // remove trailing zeros (scale < 0)...
  175. while (nibbles[cnt*2-2]*10+nibbles[cnt*2-1])=0 do
  176. cnt:=cnt-1;
  177. // ... and remove leading zeros (scale > precision)
  178. j:=0;
  179. while (nibbles[j*2]*10+nibbles[j*2+1])=0 do
  180. begin
  181. j:=j+1;
  182. exp:=exp-1;
  183. end;
  184. if IsBCDNegative(bcd) then
  185. begin
  186. b[0]:=cnt-j+1;
  187. b[1]:=not(exp+64) and $7f ;
  188. for i:=j to cnt-1 do
  189. begin
  190. bb:=nibbles[i*2]*10+nibbles[i*2+1];
  191. b[2+i-j]:=101-bb;
  192. end;
  193. if 2+cnt-j<22 then // add a 102 at the end of the number if place left.
  194. begin
  195. b[0]:=b[0]+1;
  196. b[2+cnt-j]:=102;
  197. end;
  198. end
  199. else
  200. begin
  201. b[0]:=cnt-j+1;
  202. b[1]:=(exp+64) or $80 ;
  203. for i:=j to cnt-1 do
  204. begin
  205. bb:=nibbles[i*2]*10+nibbles[i*2+1];
  206. b[2+i-j]:=1+bb;
  207. end;
  208. end;
  209. end;
  210. end;
  211. function Nvu2FmtBCE(b:pbyte):tBCD;
  212. var
  213. i,j : integer;
  214. bb,size : byte;
  215. exp : shortint;
  216. nibbles : array [0..maxfmtbcdfractionsize-1] of byte;
  217. scale : integer;
  218. begin
  219. size := b[0];
  220. if (size=1) and (b[1]=$80) then // special representation for 0
  221. result:=IntegerToBCD(0)
  222. else
  223. begin
  224. result.SignSpecialPlaces:=0; //sign positive, non blank, scale 0
  225. result.Precision:=1; //BCDNegate works only if Precision <>0
  226. if (b[1] and $80)=$80 then // then the number is positive
  227. begin
  228. exp := (b[1] and $7f)-65;
  229. for i := 0 to size-2 do
  230. begin
  231. bb := b[i+2]-1;
  232. nibbles[i*2]:=bb div 10;
  233. nibbles[i*2+1]:=(bb mod 10);
  234. end;
  235. end
  236. else
  237. begin
  238. BCDNegate(result);
  239. exp := (not(b[1]) and $7f)-65;
  240. if b[size]=102 then // last byte doesn't count if = 102
  241. size:=size-1;
  242. for i := 0 to size-2 do
  243. begin
  244. bb := 101-b[i+2];
  245. nibbles[i*2]:=bb div 10;
  246. nibbles[i*2+1]:=(bb mod 10);
  247. end;
  248. end;
  249. nibbles[(size-1)*2]:=0;
  250. result.Precision:=(size-1)*2;
  251. scale:=result.Precision-(exp*2+2);
  252. if scale>=0 then
  253. begin
  254. if (scale>result.Precision) then // need to add leading 0s
  255. begin
  256. for i:=0 to (scale-result.Precision+1) div 2 do
  257. result.Fraction[i]:=0;
  258. i:=scale-result.Precision;
  259. result.Precision:=scale;
  260. end
  261. else
  262. i:=0;
  263. j:=i;
  264. if (i=0) and (nibbles[0]=0) then // get rid of leading zero received from oci
  265. begin
  266. result.Precision:=result.Precision-1;
  267. j:=-1;
  268. end;
  269. while i<=result.Precision do // copy nibbles
  270. begin
  271. if i mod 2 =0 then
  272. result.Fraction[i div 2]:=nibbles[i-j] shl 4
  273. else
  274. result.Fraction[i div 2]:=result.Fraction[i div 2] or nibbles[i-j];
  275. i:=i+1;
  276. end;
  277. result.SignSpecialPlaces:=result.SignSpecialPlaces or scale;
  278. end
  279. else
  280. begin // add trailing zeroes, increase precision to take them into account
  281. i:=0;
  282. while i<=result.Precision do // copy nibbles
  283. begin
  284. if i mod 2 =0 then
  285. result.Fraction[i div 2]:=nibbles[i] shl 4
  286. else
  287. result.Fraction[i div 2]:=result.Fraction[i div 2] or nibbles[i];
  288. i:=i+1;
  289. end;
  290. result.Precision:=result.Precision-scale;
  291. for i := size -1 to High(result.Fraction) do
  292. result.Fraction[i] := 0;
  293. end;
  294. end;
  295. end;
  296. // TOracleConnection
  297. procedure TOracleConnection.HandleError;
  298. var errcode : sb4;
  299. buf : array[0..1023] of char;
  300. E : EOraDatabaseError;
  301. begin
  302. OCIErrorGet(FOciError,1,nil,errcode,@buf[0],1024,OCI_HTYPE_ERROR);
  303. if (Self.Name <> '') then
  304. E := EOraDatabaseError.CreateFmt('%s : %s',[Self.Name,pchar(buf)])
  305. else
  306. E := EOraDatabaseError.Create(pchar(buf));
  307. E.ErrorCode := errcode;
  308. Raise E;
  309. end;
  310. procedure TOracleConnection.GetParameters(cursor: TSQLCursor; AParams: TParams);
  311. var
  312. i : integer;
  313. odt : TODateTime;
  314. s : string;
  315. begin
  316. with cursor as TOracleCursor do for i := 0 to High(ParamBuffers) do
  317. with AParams[i] do
  318. if ParamType=ptOutput then
  319. begin
  320. if ParamBuffers[i].ind = -1 then
  321. Value:=null;
  322. case DataType of
  323. ftInteger : AsInteger := PInteger(ParamBuffers[i].buffer)^;
  324. ftFloat : AsFloat := PDouble(ParamBuffers[i].buffer)^;
  325. ftString : begin
  326. SetLength(s,ParamBuffers[i].Len);
  327. move(ParamBuffers[i].buffer^,s[1],length(s)+1);
  328. AsString:=s;
  329. end;
  330. ftDate, ftDateTime: begin
  331. OCIDateTimeGetDate(FOciUserSession, FOciError, ParamBuffers[i].buffer, @odt.year, @odt.month, @odt.day);
  332. OCIDateTimeGetTime(FOciUserSession, FOciError, ParamBuffers[i].buffer, @odt.hour, @odt.min, @odt.sec, @odt.fsec);
  333. AsDateTime := ComposeDateTime(EncodeDate(odt.year,odt.month,odt.day), EncodeTime(odt.hour,odt.min,odt.sec,odt.fsec div 1000000));
  334. end;
  335. ftFMTBcd : begin
  336. AsFMTBCD:=Nvu2FmtBCE(ParamBuffers[i].buffer);
  337. end;
  338. end;
  339. end;
  340. end;
  341. procedure TOracleConnection.DoInternalConnect;
  342. var
  343. ConnectString : string;
  344. TempServiceContext : POCISvcCtx;
  345. begin
  346. {$IfDef LinkDynamically}
  347. InitialiseOCI;
  348. {$EndIf}
  349. inherited DoInternalConnect;
  350. //todo: get rid of FUserMem, as it isn't used
  351. FUserMem := nil;
  352. // Create environment handle
  353. if OCIEnvCreate(FOciEnvironment,oci_default,nil,nil,nil,nil,0,FUserMem) <> OCI_SUCCESS then
  354. DatabaseError(SErrEnvCreateFailed,self);
  355. // Create error handle
  356. if OciHandleAlloc(FOciEnvironment,FOciError,OCI_HTYPE_ERROR,0,FUserMem) <> OCI_SUCCESS then
  357. DatabaseError(SErrHandleAllocFailed,self);
  358. // Create Server handle
  359. if OciHandleAlloc(FOciEnvironment,FOciServer,OCI_HTYPE_SERVER,0,FUserMem) <> OCI_SUCCESS then
  360. DatabaseError(SErrHandleAllocFailed,self);
  361. // Initialize Server handle
  362. if hostname='' then connectstring := databasename
  363. else connectstring := '//'+hostname+'/'+databasename;
  364. if OCIServerAttach(FOciServer,FOciError,@(ConnectString[1]),Length(ConnectString),OCI_DEFAULT) <> OCI_SUCCESS then
  365. HandleError();
  366. // Create temporary service-context handle for user authentication
  367. if OciHandleAlloc(FOciEnvironment,TempServiceContext,OCI_HTYPE_SVCCTX,0,FUserMem) <> OCI_SUCCESS then
  368. DatabaseError(SErrHandleAllocFailed,self);
  369. // Create user-session handle
  370. if OciHandleAlloc(FOciEnvironment,FOciUserSession,OCI_HTYPE_SESSION,0,FUserMem) <> OCI_SUCCESS then
  371. DatabaseError(SErrHandleAllocFailed,self);
  372. // Set the server-handle in the service-context handle
  373. if OCIAttrSet(TempServiceContext,OCI_HTYPE_SVCCTX,FOciServer,0,OCI_ATTR_SERVER,FOciError) <> OCI_SUCCESS then
  374. HandleError();
  375. // Set username and password in the user-session handle
  376. if OCIAttrSet(FOciUserSession,OCI_HTYPE_SESSION,@(Self.UserName[1]),Length(Self.UserName),OCI_ATTR_USERNAME,FOciError) <> OCI_SUCCESS then
  377. HandleError();
  378. if OCIAttrSet(FOciUserSession,OCI_HTYPE_SESSION,@(Self.Password[1]),Length(Self.Password),OCI_ATTR_PASSWORD,FOciError) <> OCI_SUCCESS then
  379. HandleError();
  380. // Authenticate
  381. if OCISessionBegin(TempServiceContext,FOciError,FOcIUserSession,OCI_CRED_RDBMS,OCI_DEFAULT) <> OCI_SUCCESS then
  382. HandleError();
  383. // Free temporary service-context handle
  384. OCIHandleFree(TempServiceContext,OCI_HTYPE_SVCCTX);
  385. end;
  386. procedure TOracleConnection.DoInternalDisconnect;
  387. var
  388. TempServiceContext : POCISvcCtx;
  389. begin
  390. inherited DoInternalDisconnect;
  391. // Create temporary service-context handle for user-disconnect
  392. if OciHandleAlloc(FOciEnvironment,TempServiceContext,OCI_HTYPE_SVCCTX,0,FUserMem) <> OCI_SUCCESS then
  393. DatabaseError(SErrHandleAllocFailed,self);
  394. // Set the server handle in the service-context handle
  395. if OCIAttrSet(TempServiceContext,OCI_HTYPE_SVCCTX,FOciServer,0,OCI_ATTR_SERVER,FOciError) <> OCI_SUCCESS then
  396. HandleError();
  397. // Set the user session handle in the service-context handle
  398. if OCIAttrSet(TempServiceContext,OCI_HTYPE_SVCCTX,FOciUserSession,0,OCI_ATTR_SESSION,FOciError) <> OCI_SUCCESS then
  399. HandleError();
  400. // Disconnect uses-session handle
  401. if OCISessionEnd(TempServiceContext,FOciError,FOcIUserSession,OCI_DEFAULT) <> OCI_SUCCESS then
  402. HandleError();
  403. // Free user-session handle
  404. OCIHandleFree(FOciUserSession,OCI_HTYPE_SESSION);
  405. // Free temporary service-context handle
  406. OCIHandleFree(TempServiceContext,OCI_HTYPE_SVCCTX);
  407. // Disconnect server handle
  408. if OCIServerDetach(FOciServer,FOciError,OCI_DEFAULT) <> OCI_SUCCESS then
  409. HandleError();
  410. // Free connection handles
  411. OCIHandleFree(FOciServer,OCI_HTYPE_SERVER);
  412. OCIHandleFree(FOciError,OCI_HTYPE_ERROR);
  413. OCIHandleFree(FOciEnvironment,OCI_HTYPE_ENV);
  414. {$IfDef LinkDynamically}
  415. ReleaseOCI;
  416. {$EndIf}
  417. end;
  418. function TOracleConnection.AllocateCursorHandle: TSQLCursor;
  419. var Cursor : TOracleCursor;
  420. begin
  421. Cursor:=TOracleCursor.Create;
  422. Result := cursor;
  423. end;
  424. procedure TOracleConnection.DeAllocateCursorHandle(var cursor: TSQLCursor);
  425. procedure FreeOraFieldBuffers(b: array of TOraFieldBuf);
  426. var i : integer;
  427. begin
  428. if Length(b) > 0 then
  429. for i := low(b) to high(b) do
  430. if b[i].DescType <> 0 then
  431. OciDescriptorFree(b[i].buffer, b[i].DescType)
  432. else
  433. freemem(b[i].buffer);
  434. end;
  435. begin
  436. with cursor as TOracleCursor do
  437. begin
  438. FreeOraFieldBuffers(FieldBuffers);
  439. FreeOraFieldBuffers(ParamBuffers);
  440. end;
  441. FreeAndNil(cursor);
  442. end;
  443. function TOracleConnection.AllocateTransactionHandle: TSQLHandle;
  444. var
  445. locRes : TOracleTrans;
  446. begin
  447. locRes := TOracleTrans.Create();
  448. try
  449. // Allocate service-context handle
  450. if OciHandleAlloc(FOciEnvironment,locRes.FOciSvcCtx,OCI_HTYPE_SVCCTX,0,FUserMem) <> OCI_SUCCESS then
  451. DatabaseError(SErrHandleAllocFailed,self);
  452. // Set the server-handle in the service-context handle
  453. if OCIAttrSet(locRes.FOciSvcCtx,OCI_HTYPE_SVCCTX,FOciServer,0,OCI_ATTR_SERVER,FOciError) <> OCI_SUCCESS then
  454. HandleError();
  455. // Set the user-session handle in the service-context handle
  456. if OCIAttrSet(locRes.FOciSvcCtx,OCI_HTYPE_SVCCTX,FOciUserSession,0,OCI_ATTR_SESSION,FOciError) <> OCI_SUCCESS then
  457. HandleError();
  458. // Allocate transaction handle
  459. if OciHandleAlloc(FOciEnvironment,locRes.FOciTrans,OCI_HTYPE_TRANS,0,FUserMem) <> OCI_SUCCESS then
  460. DatabaseError(SErrHandleAllocFailed,self);
  461. // Set the transaction handle in the service-context handle
  462. if OCIAttrSet(locRes.FOciSvcCtx,OCI_HTYPE_SVCCTX,locRes.FOciTrans,0,OCI_ATTR_TRANS,FOciError) <> OCI_SUCCESS then
  463. HandleError();
  464. except
  465. locRes.Free();
  466. raise;
  467. end;
  468. Result := locRes;
  469. end;
  470. procedure TOracleConnection.PrepareStatement(cursor: TSQLCursor;
  471. ATransaction: TSQLTransaction; buf: string; AParams: TParams);
  472. var i : integer;
  473. FOcibind : POCIDefine;
  474. OFieldType : ub2;
  475. OFieldSize : sb4;
  476. ODescType : ub4;
  477. OBuffer : pointer;
  478. stmttype : ub2;
  479. begin
  480. with cursor as TOracleCursor do
  481. begin
  482. if OCIStmtPrepare2(TOracleTrans(ATransaction.Handle).FOciSvcCtx,FOciStmt,FOciError,@buf[1],length(buf),nil,0,OCI_NTV_SYNTAX,OCI_DEFAULT) = OCI_ERROR then
  483. HandleError;
  484. // Get statement type
  485. if OCIAttrGet(FOciStmt,OCI_HTYPE_STMT,@stmttype,nil,OCI_ATTR_STMT_TYPE,FOciError) = OCI_ERROR then
  486. HandleError;
  487. case stmttype of
  488. OCI_STMT_SELECT: FStatementType := stSelect;
  489. OCI_STMT_UPDATE: FStatementType := stUpdate;
  490. OCI_STMT_DELETE: FStatementType := stDelete;
  491. OCI_STMT_INSERT: FStatementType := stInsert;
  492. OCI_STMT_CREATE,
  493. OCI_STMT_DROP,
  494. OCI_STMT_DECLARE,
  495. OCI_STMT_ALTER: FStatementType := stDDL;
  496. else
  497. FStatementType := stUnknown;
  498. end;
  499. if FStatementType in [stUpdate,stDelete,stInsert,stDDL] then
  500. FSelectable:=false;
  501. if assigned(AParams) then
  502. begin
  503. setlength(ParamBuffers,AParams.Count);
  504. for i := 0 to AParams.Count-1 do
  505. begin
  506. ODescType := 0;
  507. case AParams[i].DataType of
  508. ftSmallInt, ftInteger :
  509. begin OFieldType := SQLT_INT; OFieldSize := sizeof(integer); end;
  510. ftLargeInt :
  511. begin OFieldType := SQLT_INT; OFieldSize := sizeof(int64); end;
  512. ftFloat :
  513. begin OFieldType := SQLT_FLT; OFieldSize := sizeof(double); end;
  514. ftDate, ftDateTime :
  515. begin OFieldType := SQLT_TIMESTAMP; OFieldSize := sizeof(pointer); ODescType := OCI_DTYPE_TIMESTAMP; end;
  516. ftFixedChar, ftString :
  517. begin OFieldType := SQLT_STR; OFieldSize := 4000; end;
  518. ftFMTBcd, ftBCD :
  519. begin OFieldType := SQLT_VNU; OFieldSize := 22; end;
  520. ftBlob :
  521. begin OFieldType := SQLT_LVB; OFieldSize := 65535; end;
  522. ftMemo :
  523. begin OFieldType := SQLT_LVC; OFieldSize := 65535; end;
  524. else
  525. DatabaseErrorFmt(SUnsupportedParameter,[Fieldtypenames[AParams[i].DataType]],self);
  526. end;
  527. ParamBuffers[i].DescType := ODescType;
  528. ParamBuffers[i].Len := OFieldSize;
  529. ParamBuffers[i].Size := OFieldSize;
  530. if ODescType <> 0 then
  531. begin
  532. OBuffer := @ParamBuffers[i].buffer;
  533. OCIDescriptorAlloc(FOciEnvironment, OBuffer, ODescType, 0, nil);
  534. end
  535. else
  536. begin
  537. OBuffer := getmem(OFieldSize);
  538. ParamBuffers[i].buffer := OBuffer;
  539. end;
  540. FOciBind := nil;
  541. if AParams[i].ParamType=ptInput then
  542. begin
  543. if OCIBindByName(FOciStmt,FOcibind,FOciError,pchar(AParams[i].Name),length(AParams[i].Name),OBuffer,OFieldSize,OFieldType,@ParamBuffers[i].ind,nil,nil,0,nil,OCI_DEFAULT )= OCI_ERROR then
  544. HandleError;
  545. end
  546. else if AParams[i].ParamType=ptOutput then
  547. begin
  548. if OCIBindByName(FOciStmt,FOcibind,FOciError,pchar(AParams[i].Name),length(AParams[i].Name),nil,OFieldSize,OFieldType,nil,nil,nil,0,nil,OCI_DATA_AT_EXEC )= OCI_ERROR then
  549. HandleError;
  550. if OCIBindDynamic(FOcibind, FOciError, nil, @cbf_no_data, @parambuffers[i], @cbf_get_data) <> OCI_SUCCESS then
  551. HandleError;
  552. end;
  553. end;
  554. end;
  555. FPrepared := True;
  556. end;
  557. end;
  558. procedure TOracleConnection.SetParameters(cursor : TSQLCursor; AParams : TParams);
  559. var i : integer;
  560. year, month, day, hour, min, sec, msec : word;
  561. s : string;
  562. blobbuf : string;
  563. bloblen : ub4;
  564. begin
  565. with cursor as TOracleCursor do for i := 0 to High(ParamBuffers) do with AParams[i] do
  566. if ParamType=ptInput then
  567. begin
  568. if IsNull then ParamBuffers[i].ind := -1 else ParamBuffers[i].ind := 0;
  569. case DataType of
  570. ftSmallInt,
  571. ftInteger : PInteger(ParamBuffers[i].buffer)^ := AsInteger;
  572. ftLargeInt : PInt64(ParamBuffers[i].buffer)^ := AsLargeInt;
  573. ftFloat : PDouble(ParamBuffers[i].buffer)^ := AsFloat;
  574. ftString,
  575. ftFixedChar : begin
  576. s := asString+#0;
  577. move(s[1],parambuffers[i].buffer^,length(s)+1);
  578. end;
  579. ftDate, ftDateTime: begin
  580. DecodeDate(asDateTime,year,month,day);
  581. DecodeTime(asDateTime,hour,min,sec,msec);
  582. if OCIDateTimeConstruct(FOciUserSession, FOciError, ParamBuffers[i].buffer, year, month, day, hour, min, sec, msec*1000000, nil, 0) = OCI_ERROR then
  583. HandleError;
  584. { pb := ParamBuffers[i].buffer;
  585. pb[0] := (year div 100)+100;
  586. pb[1] := (year mod 100)+100;
  587. pb[2] := month;
  588. pb[3] := day;
  589. pb[4] := hour+1;
  590. pb[5] := minute+1;
  591. pb[6] := second+1;
  592. }
  593. end;
  594. ftFmtBCD, ftBCD : begin
  595. FmtBCD2Nvu(asFmtBCD,parambuffers[i].buffer);
  596. end;
  597. ftBlob, ftMemo : begin
  598. blobbuf := AsBlob; // todo: use AsBytes
  599. bloblen := length(blobbuf);
  600. if bloblen > 65531 then bloblen := 65531;
  601. PInteger(ParamBuffers[i].Buffer)^ := bloblen;
  602. Move(blobbuf[1], (ParamBuffers[i].Buffer+sizeof(integer))^, bloblen);
  603. //if OciLobWrite(TOracleTrans(ATransaction.Handle).FOciSvcCtx, FOciError, ParamBuffers[i].buffer, @bloblen, 1, @blobbuf[1], bloblen, OCI_ONE_PIECE, nil, nil, 0, SQLCS_IMPLICIT) = OCI_ERROR then
  604. // HandleError;
  605. end;
  606. else
  607. DatabaseErrorFmt(SUnsupportedParameter,[DataType],self);
  608. end;
  609. end;
  610. end;
  611. procedure TOracleConnection.UnPrepareStatement(cursor: TSQLCursor);
  612. begin
  613. if OCIStmtRelease(TOracleCursor(cursor).FOciStmt,FOciError,nil,0,OCI_DEFAULT)<> OCI_SUCCESS then
  614. HandleError();
  615. cursor.FPrepared:=False;
  616. end;
  617. procedure TOracleConnection.InternalStartDBTransaction(trans : TOracleTrans);
  618. begin
  619. if OCITransStart(trans.FOciSvcCtx,FOciError,DefaultTimeOut,trans.FOciFlags) <> OCI_SUCCESS then
  620. HandleError();
  621. end;
  622. function TOracleConnection.GetTransactionHandle(trans: TSQLHandle): pointer;
  623. begin
  624. Result := trans;
  625. end;
  626. function TOracleConnection.StartDBTransaction(trans: TSQLHandle; AParams: string): boolean;
  627. var
  628. x_flags : ub4;
  629. i : Integer;
  630. s : string;
  631. locTrans : TOracleTrans;
  632. begin
  633. locTrans := TOracleTrans(trans);
  634. if ( Length(AParams) = 0 ) then begin
  635. x_flags := OCI_TRANS_NEW or OCI_TRANS_READWRITE;
  636. end else begin
  637. x_flags := OCI_DEFAULT;
  638. i := 1;
  639. s := ExtractSubStr(AParams,i,StdWordDelims);
  640. while ( s <> '' ) do begin
  641. if ( s = 'readonly' ) then
  642. x_flags := x_flags and OCI_TRANS_READONLY
  643. else if ( s = 'serializable' ) then
  644. x_flags := x_flags and OCI_TRANS_SERIALIZABLE
  645. else if ( s = 'readwrite' ) then
  646. x_flags := x_flags and OCI_TRANS_READWRITE;
  647. s := ExtractSubStr(AParams,i,StdWordDelims);
  648. end;
  649. x_flags := x_flags and OCI_TRANS_NEW;
  650. end;
  651. locTrans.FOciFlags := x_flags;
  652. InternalStartDBTransaction(locTrans);
  653. Result := True;
  654. end;
  655. function TOracleConnection.Commit(trans: TSQLHandle): boolean;
  656. begin
  657. if OCITransCommit(TOracleTrans(trans).FOciSvcCtx,FOciError,OCI_DEFAULT) <> OCI_SUCCESS then
  658. HandleError();
  659. Result := True;
  660. end;
  661. function TOracleConnection.Rollback(trans: TSQLHandle): boolean;
  662. begin
  663. if OCITransRollback(TOracleTrans(trans).FOciSvcCtx,FOciError,OCI_DEFAULT) <> OCI_SUCCESS then
  664. HandleError();
  665. Result := True;
  666. end;
  667. procedure TOracleConnection.CommitRetaining(trans: TSQLHandle);
  668. begin
  669. Commit(trans);
  670. InternalStartDBTransaction(TOracleTrans(trans));
  671. end;
  672. procedure TOracleConnection.RollbackRetaining(trans: TSQLHandle);
  673. begin
  674. Rollback(trans);
  675. InternalStartDBTransaction(TOracleTrans(trans));
  676. end;
  677. procedure TOracleConnection.Execute(cursor: TSQLCursor; ATransaction: TSQLTransaction; AParams: TParams);
  678. begin
  679. if Assigned(AParams) and (AParams.Count > 0) then SetParameters(cursor, AParams);
  680. if cursor.FStatementType = stSelect then
  681. begin
  682. if OCIStmtExecute(TOracleTrans(ATransaction.Handle).FOciSvcCtx,(cursor as TOracleCursor).FOciStmt,FOciError,0,0,nil,nil,OCI_DEFAULT) = OCI_ERROR then
  683. HandleError;
  684. end
  685. else
  686. begin
  687. if OCIStmtExecute(TOracleTrans(ATransaction.Handle).FOciSvcCtx,(cursor as TOracleCursor).FOciStmt,FOciError,1,0,nil,nil,OCI_DEFAULT) = OCI_ERROR then
  688. HandleError;
  689. if Assigned(AParams) and (AParams.Count > 0) then GetParameters(cursor, AParams);
  690. end;
  691. end;
  692. function TOracleConnection.RowsAffected(cursor: TSQLCursor): TRowsCount;
  693. var rowcount: ub4;
  694. begin
  695. if Assigned(cursor) and (OCIAttrGet((cursor as TOracleCursor).FOciStmt, OCI_HTYPE_STMT, @rowcount, nil, OCI_ATTR_ROW_COUNT, FOciError) = OCI_SUCCESS) then
  696. Result:=rowcount
  697. else
  698. Result:=inherited RowsAffected(cursor);
  699. end;
  700. procedure TOracleConnection.AddFieldDefs(cursor: TSQLCursor; FieldDefs: TFieldDefs);
  701. var Param : POCIParam;
  702. counter : ub4;
  703. FieldType : TFieldType;
  704. FieldName : string;
  705. FieldSize : cardinal;
  706. OFieldType : ub2;
  707. OFieldName : Pchar;
  708. OFieldSize : ub4;
  709. OFNameLength : ub4;
  710. NumCols : ub4;
  711. FOciDefine : POCIDefine;
  712. OPrecision : sb2;
  713. OScale : sb1;
  714. ODescType : ub4;
  715. OBuffer : pointer;
  716. begin
  717. Param := nil;
  718. with cursor as TOracleCursor do
  719. begin
  720. if OCIAttrGet(FOciStmt,OCI_HTYPE_STMT,@numcols,nil,OCI_ATTR_PARAM_COUNT,FOciError) = OCI_ERROR then
  721. HandleError;
  722. // Note: needs to be cleared then allocated in one go.
  723. Setlength(FieldBuffers,numcols);
  724. for counter := 1 to numcols do
  725. begin
  726. // Clear OFieldSize. Oracle 9i, 10g doc says *ub4 but some clients use *ub2 leaving
  727. // high 16 bit untouched resulting in huge values and ORA-01062
  728. // WARNING: this does not work on big endian systems !!!!
  729. // To be tested if BE systems have this *ub2<->*ub4 problem
  730. OFieldSize:=0;
  731. ODescType :=0;
  732. if OCIParamGet(FOciStmt,OCI_HTYPE_STMT,FOciError,Param,counter) = OCI_ERROR then
  733. HandleError;
  734. if OCIAttrGet(Param,OCI_DTYPE_PARAM,@OFieldType,nil,OCI_ATTR_DATA_TYPE,FOciError) = OCI_ERROR then
  735. HandleError;
  736. if OCIAttrGet(Param,OCI_DTYPE_PARAM,@OFieldSize,nil,OCI_ATTR_DATA_SIZE,FOciError) = OCI_ERROR then
  737. HandleError;
  738. FieldSize := 0;
  739. case OFieldType of
  740. OCI_TYPECODE_NUMBER : begin
  741. if OCIAttrGet(Param,OCI_DTYPE_PARAM,@Oprecision,nil,OCI_ATTR_PRECISION,FOciError) = OCI_ERROR then
  742. HandleError;
  743. if OCIAttrGet(Param,OCI_DTYPE_PARAM,@Oscale,nil,OCI_ATTR_SCALE,FOciError) = OCI_ERROR then
  744. HandleError;
  745. if (Oscale = 0) and (Oprecision < 10) then
  746. begin
  747. if Oprecision=0 then //Number(0,0) = number(32,4)
  748. begin
  749. FieldType := ftFMTBCD;
  750. FieldSize := 4;
  751. OFieldType := SQLT_VNU;
  752. OFieldSize:= 22;
  753. end
  754. else if Oprecision < 5 then
  755. begin
  756. FieldType := ftSmallint;
  757. OFieldType := SQLT_INT;
  758. OFieldSize := sizeof(smallint);
  759. end
  760. else // OPrecision=5..9, OScale=0
  761. begin
  762. FieldType := ftInteger;
  763. OFieldType := SQLT_INT;
  764. OFieldSize:= sizeof(integer);
  765. end;
  766. end
  767. else if (Oscale = -127) {and (OPrecision=0)} then
  768. begin
  769. FieldType := ftFloat;
  770. OFieldType := SQLT_FLT;
  771. OFieldSize:=sizeof(double);
  772. end
  773. else if (Oscale >=0) and (Oscale <=4) and (OPrecision<=12) then
  774. begin
  775. FieldType := ftBCD;
  776. FieldSize := oscale;
  777. OFieldType := SQLT_VNU;
  778. OFieldSize:= 22;
  779. end
  780. else if (OPrecision-Oscale<64) and (Oscale < 64) then // limited to 63 digits before or after decimal point
  781. begin
  782. FieldType := ftFMTBCD;
  783. FieldSize := oscale;
  784. OFieldType := SQLT_VNU;
  785. OFieldSize:= 22;
  786. end
  787. else // approximation with double, best we can do
  788. begin
  789. FieldType := ftFloat;
  790. OFieldType := SQLT_FLT;
  791. OFieldSize:=sizeof(double);
  792. end;
  793. end;
  794. SQLT_LNG,
  795. OCI_TYPECODE_CHAR,
  796. OCI_TYPECODE_VARCHAR,
  797. OCI_TYPECODE_VARCHAR2 : begin
  798. FieldType := ftString;
  799. FieldSize := OFieldSize;
  800. inc(OFieldSize);
  801. OFieldType:=SQLT_STR;
  802. end;
  803. OCI_TYPECODE_DATE : FieldType := ftDate;
  804. OCI_TYPECODE_TIMESTAMP,
  805. OCI_TYPECODE_TIMESTAMP_LTZ,
  806. OCI_TYPECODE_TIMESTAMP_TZ :
  807. begin
  808. FieldType := ftDateTime;
  809. OFieldType := SQLT_TIMESTAMP;
  810. ODescType := OCI_DTYPE_TIMESTAMP;
  811. end;
  812. OCI_TYPECODE_BFLOAT,
  813. OCI_TYPECODE_BDOUBLE : begin
  814. FieldType := ftFloat;
  815. OFieldType := SQLT_BDOUBLE;
  816. OFieldSize := sizeof(double);
  817. end;
  818. SQLT_BLOB : begin
  819. FieldType := ftBlob;
  820. ODescType := OCI_DTYPE_LOB;
  821. end;
  822. SQLT_CLOB : begin
  823. FieldType := ftMemo;
  824. ODescType := OCI_DTYPE_LOB;
  825. end
  826. else
  827. FieldType := ftUnknown;
  828. end;
  829. FieldBuffers[counter-1].DescType := ODescType;
  830. if ODescType <> 0 then
  831. begin
  832. OBuffer := @FieldBuffers[counter-1].buffer;
  833. OCIDescriptorAlloc(FOciEnvironment, OBuffer, ODescType, 0, nil);
  834. OFieldSize := sizeof(pointer);
  835. end
  836. else
  837. begin
  838. OBuffer := getmem(OFieldSize);
  839. FieldBuffers[counter-1].buffer := OBuffer;
  840. end;
  841. if FieldType <> ftUnknown then
  842. begin
  843. FOciDefine := nil;
  844. if OciDefineByPos(FOciStmt,FOciDefine,FOciError,counter,OBuffer,OFieldSize,OFieldType,@FieldBuffers[counter-1].ind,nil,nil,OCI_DEFAULT) = OCI_ERROR then
  845. HandleError;
  846. end;
  847. if OCIAttrGet(Param,OCI_DTYPE_PARAM,@OFieldName,@OFNameLength,OCI_ATTR_NAME,FOciError) <> OCI_SUCCESS then
  848. HandleError;
  849. setlength(Fieldname,OFNameLength);
  850. move(OFieldName^,Fieldname[1],OFNameLength);
  851. FieldDefs.Add(FieldDefs.MakeNameUnique(FieldName), FieldType, FieldSize, False, counter);
  852. end;
  853. end;
  854. end;
  855. function TOracleConnection.Fetch(cursor: TSQLCursor): boolean;
  856. begin
  857. case OCIStmtFetch2((cursor as TOracleCursor).FOciStmt,FOciError,1,OCI_FETCH_NEXT,1,OCI_DEFAULT) of
  858. OCI_ERROR : begin
  859. Result := False;
  860. HandleError;
  861. end;
  862. OCI_NO_DATA : Result := False;
  863. OCI_SUCCESS : Result := True;
  864. OCI_SUCCESS_WITH_INFO : Begin
  865. Result := True;
  866. HandleError;
  867. end;
  868. end; {case}
  869. end;
  870. function TOracleConnection.LoadField(cursor: TSQLCursor; FieldDef: TFieldDef; buffer: pointer; out CreateBlob : boolean): boolean;
  871. var
  872. b : pbyte;
  873. size,i : byte;
  874. exp : shortint;
  875. cur : Currency;
  876. odt : TODateTime;
  877. begin
  878. CreateBlob := False;
  879. with cursor as TOracleCursor do if fieldbuffers[FieldDef.FieldNo-1].ind = -1 then
  880. Result := False
  881. else
  882. begin
  883. Result := True;
  884. case FieldDef.DataType of
  885. ftString :
  886. move(fieldbuffers[FieldDef.FieldNo-1].buffer^,buffer^,FieldDef.Size);
  887. ftBCD :
  888. begin
  889. b := fieldbuffers[FieldDef.FieldNo-1].buffer;
  890. size := b[0];
  891. cur := 0;
  892. if (b[1] and $80)=$80 then // the number is positive
  893. begin
  894. exp := (b[1] and $7f)-65;
  895. for i := 2 to size do
  896. cur := cur + (b[i]-1) * intpower(100,-(i-2)+exp);
  897. end
  898. else
  899. begin
  900. exp := (not(b[1]) and $7f)-65;
  901. for i := 2 to size-1 do
  902. cur := cur + (101-b[i]) * intpower(100,-(i-2)+exp);
  903. cur := -cur;
  904. end;
  905. move(cur,buffer^,SizeOf(Currency));
  906. end;
  907. ftFmtBCD :
  908. pBCD(buffer)^:= Nvu2FmtBCE(fieldbuffers[FieldDef.FieldNo-1].buffer);
  909. ftFloat :
  910. move(fieldbuffers[FieldDef.FieldNo-1].buffer^,buffer^,sizeof(double));
  911. ftSmallInt :
  912. move(fieldbuffers[FieldDef.FieldNo-1].buffer^,buffer^,sizeof(smallint));
  913. ftInteger :
  914. move(fieldbuffers[FieldDef.FieldNo-1].buffer^,buffer^,sizeof(integer));
  915. ftDate :
  916. begin
  917. b := fieldbuffers[FieldDef.FieldNo-1].buffer;
  918. PDateTime(buffer)^ := ComposeDateTime(EncodeDate((b[0]-100)*100+(b[1]-100),b[2],b[3]), EncodeTime(b[4]-1, b[5]-1, b[6]-1, 0));
  919. end;
  920. ftDateTime :
  921. begin
  922. OCIDateTimeGetDate(FOciUserSession, FOciError, FieldBuffers[FieldDef.FieldNo-1].buffer, @odt.year, @odt.month, @odt.day);
  923. OCIDateTimeGetTime(FOciUserSession, FOciError, FieldBuffers[FieldDef.FieldNo-1].buffer, @odt.hour, @odt.min, @odt.sec, @odt.fsec);
  924. PDateTime(buffer)^ := ComposeDateTime(EncodeDate(odt.year,odt.month,odt.day), EncodeTime(odt.hour,odt.min,odt.sec,odt.fsec div 1000000));
  925. end;
  926. ftBlob,
  927. ftMemo :
  928. CreateBlob := True;
  929. else
  930. Result := False;
  931. end;
  932. end;
  933. end;
  934. procedure TOracleConnection.LoadBlobIntoBuffer(FieldDef: TFieldDef; ABlobBuf: PBufBlobField; cursor: TSQLCursor; ATransaction: TSQLTransaction);
  935. var LobLocator: pointer;
  936. len: ub4;
  937. begin
  938. LobLocator := (cursor as TOracleCursor).FieldBuffers[FieldDef.FieldNo-1].Buffer;
  939. //if OCILobLocatorIsInit(TOracleTrans(ATransaction.Handle).FOciSvcCtx, FOciError, LobLocator, @is_init) = OCI_ERROR then
  940. // HandleError;
  941. if OciLobGetLength(TOracleTrans(ATransaction.Handle).FOciSvcCtx, FOciError, LobLocator, @len) = OCI_ERROR then
  942. HandleError;
  943. // Len - For character LOBs, it is the number of characters, for binary LOBs and BFILEs it is the number of bytes
  944. ReAllocMem(ABlobBuf^.BlobBuffer^.Buffer, len);
  945. ABlobBuf^.BlobBuffer^.Size := len;
  946. if OciLobRead(TOracleTrans(ATransaction.Handle).FOciSvcCtx, FOciError, LobLocator, @len, 1, ABlobBuf^.BlobBuffer^.Buffer, len, nil, nil, 0, SQLCS_IMPLICIT) = OCI_ERROR then
  947. HandleError;
  948. end;
  949. procedure TOracleConnection.FreeFldBuffers(cursor: TSQLCursor);
  950. begin
  951. // inherited FreeFldBuffers(cursor);
  952. end;
  953. procedure TOracleConnection.UpdateIndexDefs(IndexDefs: TIndexDefs;
  954. TableName: string);
  955. var qry : TSQLQuery;
  956. begin
  957. if not assigned(Transaction) then
  958. DatabaseError(SErrConnTransactionnSet);
  959. // Get table name into canonical format
  960. if (length(TableName)>2) and (TableName[1]=ObjectQuote) and (TableName[length(TableName)]=ObjectQuote) then
  961. TableName := AnsiDequotedStr(TableName, ObjectQuote)
  962. else
  963. TableName := UpperCase(TableName); //ANSI SQL: the name of an identifier (such as table names) are implicitly converted to uppercase, unless double quotes are used when referring to the identifier.
  964. qry := tsqlquery.Create(nil);
  965. qry.transaction := Transaction;
  966. qry.database := Self;
  967. with qry do
  968. begin
  969. ReadOnly := True;
  970. sql.clear;
  971. sql.add('SELECT '+
  972. 'i.INDEX_NAME, '+
  973. 'c.COLUMN_NAME, '+
  974. 'p.CONSTRAINT_TYPE '+
  975. 'FROM ALL_INDEXES i, ALL_IND_COLUMNS c,ALL_CONSTRAINTS p '+
  976. 'WHERE '+
  977. 'i.OWNER=c.INDEX_OWNER AND '+
  978. 'i.INDEX_NAME=c.INDEX_NAME AND '+
  979. 'p.INDEX_NAME(+)=i.INDEX_NAME AND '+
  980. 'c.TABLE_NAME = ''' + TableName + ''' '+
  981. 'ORDER by i.INDEX_NAME,c.COLUMN_POSITION');
  982. open;
  983. end;
  984. while not qry.eof do with IndexDefs.AddIndexDef do
  985. begin
  986. Name := trim(qry.fields[0].asstring);
  987. Fields := trim(qry.Fields[1].asstring);
  988. If UpperCase(qry.fields[2].asString)='P' then options := options + [ixPrimary];
  989. If UpperCase(qry.fields[2].asString)='U' then options := options + [ixUnique];
  990. qry.next;
  991. while (name = qry.fields[0].asstring) and (not qry.eof) do
  992. begin
  993. Fields := Fields + ';' + trim(qry.Fields[2].asstring);
  994. qry.next;
  995. end;
  996. end;
  997. qry.close;
  998. qry.free;
  999. end;
  1000. function TOracleConnection.GetSchemaInfoSQL(SchemaType: TSchemaType;
  1001. SchemaObjectName, SchemaPattern: string): string;
  1002. var s : string;
  1003. begin
  1004. case SchemaType of
  1005. stTables : s := 'SELECT '+
  1006. '''' + DatabaseName + ''' as catalog_name, '+
  1007. 'sys_context( ''userenv'', ''current_schema'' ) as schema_name, '+
  1008. 'TABLE_NAME '+
  1009. 'FROM USER_CATALOG ' +
  1010. 'WHERE '+
  1011. 'TABLE_TYPE<>''SEQUENCE'' '+
  1012. 'ORDER BY TABLE_NAME';
  1013. stSysTables : s := 'SELECT '+
  1014. '''' + DatabaseName + ''' as catalog_name, '+
  1015. 'OWNER as schema_name, '+
  1016. 'TABLE_NAME '+
  1017. 'FROM ALL_CATALOG ' +
  1018. 'WHERE '+
  1019. 'TABLE_TYPE<>''SEQUENCE'' '+
  1020. 'ORDER BY TABLE_NAME';
  1021. stColumns : s := 'SELECT '+
  1022. 'COLUMN_NAME, '+
  1023. 'DATA_TYPE as column_datatype, '+
  1024. 'CHARACTER_SET_NAME, '+
  1025. 'NULLABLE as column_nullable, '+
  1026. 'DATA_LENGTH as column_length, '+
  1027. 'DATA_PRECISION as column_precision, '+
  1028. 'DATA_SCALE as column_scale '+
  1029. {DATA_DEFAULT is type LONG; no support for that in oracleconnection so removed this from query}
  1030. 'FROM ALL_TAB_COLUMNS '+
  1031. 'WHERE Upper(TABLE_NAME) = '''+UpperCase(SchemaObjectName)+''' '+
  1032. 'ORDER BY COLUMN_NAME';
  1033. // Columns of tables, views and clusters accessible to user; hidden columns are filtered out.
  1034. stProcedures : s := 'SELECT '+
  1035. 'case when PROCEDURE_NAME is null then OBJECT_NAME ELSE OBJECT_NAME || ''.'' || PROCEDURE_NAME end AS procedure_name '+
  1036. 'FROM USER_PROCEDURES ';
  1037. else
  1038. DatabaseError(SMetadataUnavailable)
  1039. end; {case}
  1040. result := s;
  1041. end;
  1042. constructor TOracleConnection.Create(AOwner: TComponent);
  1043. begin
  1044. inherited Create(AOwner);
  1045. FConnOptions := FConnOptions + [sqEscapeRepeat];
  1046. FUserMem := nil;
  1047. end;
  1048. { TOracleConnectionDef }
  1049. class function TOracleConnectionDef.TypeName: String;
  1050. begin
  1051. Result:='Oracle';
  1052. end;
  1053. class function TOracleConnectionDef.ConnectionClass: TSQLConnectionClass;
  1054. begin
  1055. Result:=TOracleConnection;
  1056. end;
  1057. class function TOracleConnectionDef.Description: String;
  1058. begin
  1059. Result:='Connect to an Oracle database directly via the client library';
  1060. end;
  1061. class function TOracleConnectionDef.DefaultLibraryName: String;
  1062. begin
  1063. {$IfDef LinkDynamically}
  1064. Result:=ocilib;
  1065. {$else}
  1066. Result:='';
  1067. {$endif}
  1068. end;
  1069. class function TOracleConnectionDef.LoadFunction: TLibraryLoadFunction;
  1070. begin
  1071. {$IfDef LinkDynamically}
  1072. Result:=@InitialiseOCI;
  1073. {$else}
  1074. Result:=Nil;
  1075. {$endif}
  1076. end;
  1077. class function TOracleConnectionDef.UnLoadFunction: TLibraryUnLoadFunction;
  1078. begin
  1079. {$IfDef LinkDynamically}
  1080. Result:=@ReleaseOCI;
  1081. {$else}
  1082. Result:=Nil;
  1083. {$endif}
  1084. end;
  1085. class function TOracleConnectionDef.LoadedLibraryName: string;
  1086. begin
  1087. {$IfDef LinkDynamically}
  1088. Result:=OCILoadedLibrary;
  1089. {$else}
  1090. Result:='';
  1091. {$endif}
  1092. end;
  1093. { TOracleTrans }
  1094. destructor TOracleTrans.Destroy();
  1095. begin
  1096. OCIHandleFree(FOciTrans,OCI_HTYPE_TRANS);
  1097. OCIHandleFree(FOciSvcCtx,OCI_HTYPE_SVCCTX);
  1098. inherited Destroy();
  1099. end;
  1100. initialization
  1101. RegisterConnection(TOracleConnectionDef);
  1102. finalization
  1103. UnRegisterConnection(TOracleConnectionDef);
  1104. end.