1 <?xml version=
"1.0" encoding=
"UTF-8"?>
2 <!DOCTYPE script:module PUBLIC
"-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
3 <script:module xmlns:
script=
"http://openoffice.org/2000/script" script:
name=
"Database" script:
language=
"StarBasic">REM =======================================================================================================================
4 REM === The Access2Base library is a part of the LibreOffice project. ===
5 REM === Full documentation is available on http://www.access2base.com ===
6 REM =======================================================================================================================
13 REM -----------------------------------------------------------------------------------------------------------------------
14 REM --- CLASS ROOT FIELDS ---
15 REM -----------------------------------------------------------------------------------------------------------------------
17 Private _Type As String
' Must be DATABASE
18 Private _This As Object
' Workaround for absence of This builtin function
19 Private _DbConnect As Integer
' DBCONNECTxxx constants
20 Private Title As String
21 Private Document As Object
' com.sun.star.comp.dba.ODatabaseDocument or SwXTextDocument or ScModelObj
22 Private Connection As Object
' com.sun.star.sdbc.drivers.OConnectionWrapper or com.sun.star.sdbc.XConnection
24 Private _ReadOnly As Boolean
25 Private MetaData As Object
' interface XDatabaseMetaData
26 Private _RDBMS As Integer
' DBMS constants
27 Private _ColumnTypes() As Variant
' Part of Metadata.GetTypeInfo()
28 Private _ColumnTypeNames() As Variant
29 Private _ColumnPrecisions() As Variant
30 Private _ColumnTypesReference() As Variant
31 Private _ColumnTypesAlias() As Variant
' To what should a field whose origin is another DBMS be converted ? See DataTypes By RDBMS.ods
32 Private _BinaryStream As Boolean
' False = binary fields must NOT be streamed f.i. via ReadAllBytes or WriteAllBytes
33 Private Form As Object
' com.sun.star.form.XForm
34 Private FormName As String
35 Private RecordsetMax As Integer
36 Private RecordsetsColl As Object
' Collection of active recordsets
38 REM -----------------------------------------------------------------------------------------------------------------------
39 REM --- CONSTRUCTORS / DESTRUCTORS ---
40 REM -----------------------------------------------------------------------------------------------------------------------
41 Private Sub Class_Initialize()
46 Set Document = Nothing
47 Set Connection = Nothing
50 Set MetaData = Nothing
52 _ColumnTypes = Array()
53 _ColumnTypeNames = Array()
54 _ColumnPrecisions = Array()
55 _ColumnTypesReference = Array()
56 _ColumnTypesAlias() = Array()
59 FormName =
""
61 Set RecordsetsColl = New Collection
62 End Sub
' Constructor
64 REM -----------------------------------------------------------------------------------------------------------------------
65 Private Sub Class_Terminate()
66 On Local Error Resume Next
67 Call CloseAllRecordsets()
68 If _DbConnect
<> DBCONNECTANY Then
69 If Not IsNull(Connection) Then
72 Set Connection = Nothing
77 Call Class_Initialize()
78 End Sub
' Destructor
80 REM -----------------------------------------------------------------------------------------------------------------------
82 Call Class_Terminate()
83 End Sub
' Explicit destructor
87 REM -----------------------------------------------------------------------------------------------------------------------
88 REM --- CLASS GET/LET/SET PROPERTIES ---
89 REM -----------------------------------------------------------------------------------------------------------------------
91 Property Get Connect() As String
92 Connect = _PropertyGet(
"Connect
")
93 End Property
' Connect (get)
95 REM -----------------------------------------------------------------------------------------------------------------------
96 Property Get Name() As String
97 Name = _PropertyGet(
"Name
")
98 End Property
' Name (get)
100 REM -----------------------------------------------------------------------------------------------------------------------
101 Property Get ObjectType() As String
102 ObjectType = _PropertyGet(
"ObjectType
")
103 End Property
' ObjectType (get)
105 REM -----------------------------------------------------------------------------------------------------------------------
106 Property Get Version() As String
107 Version = _PropertyGet(
"Version
")
108 End Property
' Version (get)
110 REM -----------------------------------------------------------------------------------------------------------------------
111 REM --- CLASS METHODS ---
112 REM -----------------------------------------------------------------------------------------------------------------------
114 REM -----------------------------------------------------------------------------------------------------------------------
115 Public Function mClose() As Variant
116 ' Close the database
118 If _ErrorHandler() Then On Local Error Goto Error_Function
119 Const cstThisSub =
"Database.Close
"
120 Utils._SetCalledSub(cstThisSub)
122 If _DbConnect
<> DBCONNECTANY Then Goto Error_NotApplicable
126 Set Connection = Nothing
130 Utils._ResetCalledSub(cstThisSub)
133 TraceError(TRACEFATAL, ERRMETHOD, Utils._CalledSub(),
0,
1, cstThisSub)
136 TraceError(TRACEABORT, Err, Utils._CalledSub(), Erl)
138 End Function
' (m)Close
140 REM -----------------------------------------------------------------------------------------------------------------------
141 Public Sub CloseAllRecordsets()
142 ' Clean all recordsets for housekeeping
144 Dim sRecordsets() As String, i As Integer, oRecordset As Object
145 On Local Error Goto Exit_Sub
147 If IsNull(RecordsetsColl) Then Exit Sub
148 If RecordsetsColl.Count
< 1 Then Exit Sub
149 For i =
1 To RecordsetsColl.Count
150 Set oRecordset = RecordsetsColl.Item(i)
151 oRecordset.mClose(False)
' Do not remove entry in collection
153 Set RecordsetsColl = New Collection
158 End Sub
' CloseAllRecordsets V0.9
.5
160 REM -----------------------------------------------------------------------------------------------------------------------
161 Public Function CreateQueryDef(ByVal Optional pvQueryName As Variant _
162 , ByVal Optional pvSql As Variant _
163 , ByVal Optional pvOption As Variant _
165 'Return a (new) QueryDef object based on SQL statement
166 Const cstThisSub =
"Database.CreateQueryDef
"
167 Utils._SetCalledSub(cstThisSub)
170 Dim oQuery As Object, oQueries As Object, i As Integer, sQueryName As String
172 If _ErrorHandler() Then On Local Error Goto Error_Function
174 Set CreateQueryDef = Nothing
175 If _DbConnect
<> DBCONNECTBASE Then Goto Error_NotApplicable
176 If IsMissing(pvQueryName) Then Call _TraceArguments()
177 If IsMissing(pvSql) Then Call _TraceArguments()
178 If IsMissing(pvOption) Then pvOption = cstNull
180 If Not Utils._CheckArgument(pvQueryName,
1, vbString) Then Goto Exit_Function
181 If pvQueryName =
"" Then Call _TraceArguments()
182 If Not Utils._CheckArgument(pvSql,
2, vbString) Then Goto Exit_Function
183 If pvSql =
"" Then Call _TraceArguments()
184 If Not Utils._CheckArgument(pvOption,
3, Utils._AddNumeric(), Array(cstNull, dbSQLPassThrough)) Then Goto Exit_Function
186 If _ReadOnly Then Goto Error_NoUpdate
188 Set oQuery = CreateUnoService(
"com.sun.star.sdb.QueryDefinition
")
189 oQuery.rename(pvQueryName)
190 oQuery.Command = _ReplaceSquareBrackets(pvSql)
191 oQuery.EscapeProcessing = Not ( pvOption = dbSQLPassThrough )
193 Set oQueries = Document.DataSource.getQueryDefinitions()
195 For i =
0 To .getCount() -
1
196 sQueryName = .getByIndex(i).Name
197 If UCase(sQueryName) = UCase(pvQueryName) Then
198 TraceError(TRACEWARNING, ERRQUERYDEFDELETED, Utils._CalledSub(),
0, False, sQueryName)
199 .removeByName(sQueryName)
203 .insertByName(pvQueryName, oQuery)
205 Set CreateQueryDef = QueryDefs(pvQueryName)
208 Utils._ResetCalledSub(cstThisSub)
211 TraceError(TRACEFATAL, ERRMETHOD, Utils._CalledSub(),
0,
1, cstThisSub)
214 TraceError(TRACEFATAL, ERRNOTUPDATABLE, Utils._CalledSub(),
0)
217 TraceError(TRACEABORT, Err, cstThisSub, Erl)
219 End Function
' CreateQueryDef V1.1
.0
221 REM -----------------------------------------------------------------------------------------------------------------------
222 Public Function CreateTableDef(ByVal Optional pvTableName As Variant) As Object
223 'Return a (new/empty) TableDef object
224 Const cstThisSub =
"Database.CreateTableDef
"
225 Utils._SetCalledSub(cstThisSub)
227 Dim oTable As Object, oTables As Object, sTables() As String
228 Dim i As Integer, sTableName As String, oNewTable As Object
229 Dim vNameComponents() As Variant, iNames As Integer
231 If _ErrorHandler() Then On Local Error Goto Error_Function
233 Set CreateTableDef = Nothing
234 If _DbConnect
<> DBCONNECTBASE Then Goto Error_NotApplicable
235 If IsMissing(pvTableName) Then Call _TraceArguments()
237 If Not Utils._CheckArgument(pvTableName,
1, vbString) Then Goto Exit_Function
238 If pvTableName =
"" Then Call _TraceArguments()
240 If _ReadOnly Then Goto Error_NoUpdate
242 Set oTables = Connection.getTables
244 sTables = .ElementNames()
245 ' Check existence of object and find its exact (case-sensitive) name
246 For i =
0 To UBound(sTables)
247 If UCase(pvTableName) = UCase(sTables(i)) Then
248 sTableName = sTables(i)
249 TraceError(TRACEWARNING, ERRTABLEDEFDELETED, Utils._CalledSub(),
0, False, sTableName)
250 .dropByName(sTableName)
254 Set oNewTable = New DataDef
255 oNewTable._Type = OBJTABLEDEF
256 oNewTable._Name = pvTableName
257 vNameComponents = Split(pvTableName,
".
")
258 iNames = UBound(vNameComponents)
259 If iNames
>=
2 Then oNewtable.CatalogName = vNameComponents(iNames -
2) Else oNewTable.CatalogName =
""
260 If iNames
>=
1 Then oNewtable.SchemaName = vNameComponents(iNames -
1) Else oNewTable.SchemaName =
""
261 oNewtable.TableName = vNameComponents(iNames)
262 Set oNewTable._ParentDatabase = _This
263 Set oNewTable.TableDescriptor = .createDataDescriptor()
264 oNewTable.TableDescriptor.CatalogName = oNewTable.CatalogName
265 oNewTable.TableDescriptor.SchemaName = oNewTable.SchemaName
266 oNewTable.TableDescriptor.Name = oNewTable.TableName
267 oNewTable.TableDescriptor.Type =
"TABLE
"
270 Set CreateTabledef = oNewTable
273 Utils._ResetCalledSub(cstThisSub)
276 TraceError(TRACEFATAL, ERRMETHOD, Utils._CalledSub(),
0,
1, cstThisSub)
279 TraceError(TRACEFATAL, ERRNOTUPDATABLE, Utils._CalledSub(),
0)
282 TraceError(TRACEABORT, Err, cstThisSub, Erl)
284 End Function
' CreateTableDef V1.1
.0
286 REM -----------------------------------------------------------------------------------------------------------------------
287 Public Function DAvg( _
288 ByVal Optional psExpr As String _
289 , ByVal Optional psDomain As String _
290 , ByVal Optional pvCriteria As Variant _
292 ' Return average of scope
293 Const cstThisSub =
"Database.DAvg
"
294 Utils._SetCalledSub(cstThisSub)
295 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
296 DAvg = _DFunction(
"AVG
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
297 Utils._ResetCalledSub(cstThisSub)
298 End Function
' DAvg
300 REM -----------------------------------------------------------------------------------------------------------------------
301 Public Function DCount( _
302 ByVal Optional psExpr As String _
303 , ByVal Optional psDomain As String _
304 , ByVal Optional pvCriteria As Variant _
306 ' Return # of occurrences of scope
307 Const cstThisSub =
"Database.DCount
"
308 Utils._SetCalledSub(cstThisSub)
309 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
310 DCount = _DFunction(
"COUNT
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
311 Utils._ResetCalledSub(cstThisSub)
312 End Function
' DCount
314 REM -----------------------------------------------------------------------------------------------------------------------
315 Public Function DLookup( _
316 ByVal Optional psExpr As String _
317 , ByVal Optional psDomain As String _
318 , ByVal Optional pvCriteria As Variant _
319 , ByVal Optional pvOrderClause As Variant _
322 ' Return a value within a table
323 'Arguments: psExpr: an SQL expression
324 ' psDomain: a table- or queryname
325 ' pvCriteria: an optional WHERE clause
326 ' pcOrderClause: an optional order clause incl.
"DESC
" if relevant
327 'Return: Value of the psExpr if found, else Null.
328 'Author: inspired from Allen Browne. http://allenbrowne.com/ser-
42.html
330 ' 1. To find the last value, include DESC in the OrderClause, e.g.:
331 ' DLookup(
"[Surname]
& [FirstName]
",
"tblClient
", ,
"ClientID DESC
")
332 ' 2. To find the lowest non-null value of a field, use the Criteria, e.g.:
333 ' DLookup(
"ClientID
",
"tblClient
",
"Surname Is Not Null
" ,
"Surname
")
335 Const cstThisSub =
"Database.DLookup
"
336 Utils._SetCalledSub(cstThisSub)
337 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
338 DLookup = _DFunction(
"", psExpr, psDomain _
339 , Iif(IsMissing(pvCriteria),
"", pvCriteria) _
340 , Iif(IsMissing(pvOrderClause),
"", pvOrderClause) _
342 Utils._ResetCalledSub(cstThisSub)
343 End Function
' DLookup
345 REM -----------------------------------------------------------------------------------------------------------------------
346 Public Function DMax( _
347 ByVal Optional psExpr As String _
348 , ByVal Optional psDomain As String _
349 , ByVal Optional pvCriteria As Variant _
351 ' Return maximum of scope
352 Const cstThisSub =
"Database.DMax
"
353 Utils._SetCalledSub(cstThisSub)
354 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
355 DMax = _DFunction(
"MAX
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
356 Utils._ResetCalledSub(cstThisSub)
357 End Function
' DMax
359 REM -----------------------------------------------------------------------------------------------------------------------
360 Public Function DMin( _
361 ByVal Optional psExpr As String _
362 , ByVal Optional psDomain As String _
363 , ByVal Optional pvCriteria As Variant _
365 ' Return minimum of scope
366 Const cstThisSub =
"Database.DMin
"
367 Utils._SetCalledSub(cstThisSub)
368 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
369 DMin = _DFunction(
"MIN
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
370 Utils._ResetCalledSub(cstThisSub)
371 End Function
' DMin
373 REM -----------------------------------------------------------------------------------------------------------------------
374 Public Function DStDev( _
375 ByVal Optional psExpr As String _
376 , ByVal Optional psDomain As String _
377 , ByVal Optional pvCriteria As Variant _
379 ' Return standard deviation of scope
380 Const cstThisSub =
"Database.DStDev
"
381 Utils._SetCalledSub(cstThisSub)
382 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
383 DStDev = _DFunction(
"STDDEV_SAMP
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
' STDDEV not STDEV !
384 Utils._ResetCalledSub(cstThisSub)
385 End Function
' DStDev
387 REM -----------------------------------------------------------------------------------------------------------------------
388 Public Function DStDevP( _
389 ByVal Optional psExpr As String _
390 , ByVal Optional psDomain As String _
391 , ByVal Optional pvCriteria As Variant _
393 ' Return standard deviation of scope
394 Const cstThisSub =
"Database.DStDevP
"
395 Utils._SetCalledSub(cstThisSub)
396 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
397 DStDevP = _DFunction(
"STDDEV_POP
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
' STDDEV not STDEV !
398 Utils._ResetCalledSub(cstThisSub)
399 End Function
' DStDevP
401 REM -----------------------------------------------------------------------------------------------------------------------
402 Public Function DSum( _
403 ByVal Optional psExpr As String _
404 , ByVal Optional psDomain As String _
405 , ByVal Optional pvCriteria As Variant _
407 ' Return sum of scope
408 Const cstThisSub =
"Database.DSum
"
409 Utils._SetCalledSub(cstThisSub)
410 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
411 DSum = _DFunction(
"SUM
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
412 Utils._ResetCalledSub(cstThisSub)
413 End Function
' DSum
415 REM -----------------------------------------------------------------------------------------------------------------------
416 Public Function DVar( _
417 ByVal Optional psExpr As String _
418 , ByVal Optional psDomain As String _
419 , ByVal Optional pvCriteria As Variant _
421 ' Return variance of scope
422 Const cstThisSub =
"Database.DVar
"
423 Utils._SetCalledSub(cstThisSub)
424 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
425 DVar = _DFunction(
"VAR_SAMP
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
426 Utils._ResetCalledSub(cstThisSub)
427 End Function
' DVar
429 REM -----------------------------------------------------------------------------------------------------------------------
430 Public Function DVarP( _
431 ByVal Optional psExpr As String _
432 , ByVal Optional psDomain As String _
433 , ByVal Optional pvCriteria As Variant _
435 ' Return variance of scope
436 Const cstThisSub =
"Database.DVarP
"
437 Utils._SetCalledSub(cstThisSub)
438 If IsMissing(psExpr) Or IsMissing(psDomain) Then Call _TraceArguments()
439 DVarP = _DFunction(
"VAR_POP
", psExpr, psDomain, Iif(IsMissing(pvCriteria),
"", pvCriteria),
"")
440 Utils._ResetCalledSub(cstThisSub)
441 End Function
' DVarP
443 REM -----------------------------------------------------------------------------------------------------------------------
444 Public Function getProperty(Optional ByVal pvProperty As Variant) As Variant
445 ' Return property value of psProperty property name
447 Utils._SetCalledSub(
"Database.getProperty
")
448 If IsMissing(pvProperty) Then Call _TraceArguments()
449 getProperty = _PropertyGet(pvProperty)
450 Utils._ResetCalledSub(
"Database.getProperty
")
452 End Function
' getProperty
454 REM -----------------------------------------------------------------------------------------------------------------------
455 Public Function hasProperty(ByVal Optional pvProperty As Variant) As Boolean
456 ' Return True if object has a valid property called pvProperty (case-insensitive comparison !)
458 If IsMissing(pvProperty) Then hasProperty = PropertiesGet._hasProperty(_Type, _PropertiesList()) Else hasProperty = PropertiesGet._hasProperty(_Type, _PropertiesList(), pvProperty)
461 End Function
' hasProperty
463 REM -----------------------------------------------------------------------------------------------------------------------
464 Public Function OpenRecordset(ByVal Optional pvSource As Variant _
465 , ByVal Optional pvType As Variant _
466 , ByVal Optional pvOptions As Variant _
467 , ByVal Optional pvLockEdit As Variant _
469 'Return a Recordset object based on Source (= SQL, table or query name)
471 Const cstThisSub =
"Database.OpenRecordset
"
472 Utils._SetCalledSub(cstThisSub)
475 Dim lCommandType As Long, sCommand As String, oObject As Object
476 Dim sSource As String, i As Integer, iCount As Integer
477 Dim sObjects() As String, bFound As Boolean, oTables As Object, oQueries As Object
479 If _ErrorHandler() Then On Local Error Goto Error_Function
480 Set oObject = Nothing
481 If IsMissing(pvSource) Then Call _TraceArguments()
482 If pvSource =
"" Then Call _TraceArguments()
483 If IsMissing(pvType) Then
486 If Not Utils._CheckArgument(pvType,
2, Utils._AddNumeric(), dbOpenForwardOnly) Then Goto Exit_Function
488 If IsMissing(pvOptions) Then
491 If Not Utils._CheckArgument(pvOptions,
3, Utils._AddNumeric(), dbSQLPassThrough) Then Goto Exit_Function
493 If IsMissing(pvLockEdit) Then
496 If Not Utils._CheckArgument(pvLockEdit,
4, Utils._AddNumeric(), dbReadOnly) Then Goto Exit_Function
499 sSource = Split(UCase(Trim(pvSource)),
" ")(
0)
501 Case sSource =
"SELECT
"
502 lCommandType = com.sun.star.sdb.CommandType.COMMAND
503 sCommand = _ReplaceSquareBrackets(pvSource)
505 sSource = UCase(Trim(pvSource))
507 Set oTables = Connection.getTables
508 sObjects = oTables.ElementNames()
510 For i =
0 To UBound(sObjects)
511 If sSource = UCase(sObjects(i)) Then
512 sCommand = sObjects(i)
518 lCommandType = com.sun.star.sdb.CommandType.TABLE
521 Set oQueries = Connection.getQueries
522 sObjects = oQueries.ElementNames()
523 For i =
0 To UBound(sObjects)
524 If sSource = UCase(sObjects(i)) Then
525 sCommand = sObjects(i)
530 If Not bFound Then Goto Trace_NotFound
531 lCommandType = com.sun.star.sdb.CommandType.QUERY
535 Set oObject = New Recordset
537 ._CommandType = lCommandType
541 ._ForwardOnly = ( pvType = dbOpenForwardOnly )
542 ._PassThrough = ( pvOptions = dbSQLPassThrough )
543 ._ReadOnly = ( (pvLockEdit = dbReadOnly) Or _ReadOnly )
545 Set ._ParentDatabase = _This
547 RecordsetMax = RecordsetMax +
1
548 ._Name = Format(RecordsetMax,
"0000000")
549 RecordsetsColl.Add(oObject, UCase(._Name))
552 If Not ( oObject._BOF And oObject._EOF ) Then oObject.MoveFirst()
' Do nothing if resultset empty
555 Set OpenRecordset = oObject
556 Set oObject = Nothing
557 Utils._ResetCalledSub(cstThisSub)
560 TraceError(TRACEABORT, Err, cstThisSub, Erl)
563 TraceError(TRACEFATAL, ERROBJECTNOTFOUND, Utils._CalledSub(),
0, , Array(_GetLabel(
"TABLE
")
& "/
" & _GetLabel(
"QUERY
"), pvSource))
565 End Function
' OpenRecordset V1.1
.0
567 REM -----------------------------------------------------------------------------------------------------------------------
568 Public Function OpenSQL(Optional ByVal pvSQL As Variant _
569 , Optional ByVal pvOption As Variant _
571 ' Return True if the execution of the SQL statement was successful
572 ' SQL must contain a SELECT query
573 ' pvOption can force pass through mode
575 If _ErrorHandler() Then On Local Error Goto Error_Function
577 Const cstThisSub =
"Database.OpenSQL
"
578 Utils._SetCalledSub(cstThisSub)
581 If IsMissing(pvSQL) Then Call _TraceArguments()
582 If Not Utils._CheckArgument(pvSQL,
1, vbString) Then Goto Exit_Function
584 If IsMissing(pvOption) Then
587 If Not Utils._CheckArgument(pvOption,
2, Utils._AddNumeric(), Array(dbSQLPassThrough, cstNull)) Then Goto Exit_Function
589 If _DbConnect
<> DBCONNECTBASE And _DbConnect
<> DBCONNECTFORM Then Goto Error_NotApplicable
591 Dim oURL As New com.sun.star.util.URL, oDispatch As Object
592 Dim vArgs(
8) as New com.sun.star.beans.PropertyValue
594 oURL.Complete =
".component:DB/DataSourceBrowser
"
595 oDispatch = StarDesktop.queryDispatch(oURL,
"_Blank
",
8)
597 vArgs(
0).Name =
"ActiveConnection
" : vArgs(
0).Value = Connection
598 vArgs(
1).Name =
"CommandType
" : vArgs(
1).Value = com.sun.star.sdb.CommandType.COMMAND
599 vArgs(
2).Name =
"Command
" : vArgs(
2).Value = _ReplaceSquareBrackets(pvSQL)
600 vArgs(
3).Name =
"ShowMenu
" : vArgs(
3).Value = True
601 vArgs(
4).Name =
"ShowTreeView
" : vArgs(
4).Value = False
602 vArgs(
5).Name =
"ShowTreeViewButton
" : vArgs(
5).Value = False
603 vArgs(
6).Name =
"Filter
" : vArgs(
6).Value =
""
604 vArgs(
7).Name =
"ApplyFilter
" : vArgs(
7).Value = False
605 vArgs(
8).Name =
"EscapeProcessing
" : vArgs(
8).Value = CBool(Not ( pvOption = dbSQLPassThrough ))
607 oDispatch.dispatch(oURL, vArgs)
613 TraceError(TRACEABORT, Err,
"OpenSQL
", Erl)
616 TraceError(TRACEFATAL, ERRSQLSTATEMENT, Utils._CalledSub(),
0, , pvSQL)
619 TraceError(TRACEFATAL, ERRMETHOD, Utils._CalledSub(),
0,
1, cstThisSub)
621 End Function
' OpenSQL V1.1
.0
623 REM -----------------------------------------------------------------------------------------------------------------------
624 Public Function OutputTo(ByVal pvObjectType As Variant _
625 , ByVal Optional pvObjectName As Variant _
626 , ByVal Optional pvOutputFormat As Variant _
627 , ByVal Optional pvOutputFile As Variant _
628 , ByVal Optional pvAutoStart As Variant _
629 , ByVal Optional pvTemplateFile As Variant _
630 , ByVal Optional pvEncoding As Variant _
631 , ByVal Optional pvQuality As Variant _
632 , ByRef Optional pvHeaders As Variant _
633 , ByRef Optional pvData As Variant _
635 'Supported: acFormatHTML, acFormatODS, acFormatXLS, acFormatXLSX, acFormatTXT for tables and queries
636 'pvHeaders and pvData (unpublished) when pvObjectType = acOutputArray
638 If _ErrorHandler() Then On Local Error Goto Error_Function
639 Const cstThisSub =
"Database.OutputTo
"
640 Utils._SetCalledSub(cstThisSub)
644 If Not Utils._CheckArgument(pvObjectType,
1, Utils._AddNumeric(), Array(acOutputTable, acOutputQuery, acOutputArray)) Then Goto Exit_Function
645 If IsMissing(pvObjectName) Then Call _TraceArguments()
646 If Not Utils._CheckArgument(pvObjectName,
2, vbString) Then Goto Exit_Function
647 If IsMissing(pvOutputFormat) Then pvOutputFormat =
""
648 If Not Utils._CheckArgument(pvOutputFormat,
3, vbString) Then Goto Exit_Function
649 If pvOutputFormat
<> "" Then
650 If Not Utils._CheckArgument(UCase(pvOutputFormat),
3, vbString, Array( _
651 UCase(acFormatHTML),
"HTML
" _
652 , UCase(acFormatODS),
"ODS
" _
653 , UCase(acFormatXLS),
"XLS
" _
654 , UCase(acFormatXLSX),
"XLSX
" _
655 , UCase(acFormatTXT),
"TXT
",
"CSV
" _
657 Then Goto Exit_Function
' A
2nd time to allow case unsensitivity
659 If IsMissing(pvOutputFile) Then pvOutputFile =
""
660 If Not Utils._CheckArgument(pvOutputFile,
4, vbString) Then Goto Exit_Function
661 If IsMissing(pvAutoStart) Then pvAutoStart = False
662 If Not Utils._CheckArgument(pvAutoStart,
5, vbBoolean) Then Goto Exit_Function
663 If IsMissing(pvTemplateFile) Then pvTemplateFile =
""
664 If Not Utils._CheckArgument(pvTemplateFile,
6, vbString) Then Goto Exit_Function
665 If IsMissing(pvEncoding) Then pvEncoding =
0
666 If Not Utils._CheckArgument(pvEncoding,
7, _AddNumeric()) Then Goto Exit_Function
667 If IsMissing(pvQuality) Then pvQuality = acExportQualityPrint
668 If Not Utils._CheckArgument(pvQuality,
7, _AddNumeric(), Array(acExportQualityPrint, acExportQualityScreen)) Then Goto Exit_Function
669 If pvObjectType = acOutputArray Then
670 If IsMissing(pvHeaders) Or IsMissing(pvData) Then Call _TraceArguments()
671 pvOutputFormat =
"HTML
"
674 Dim sOutputFile As String, oTable As Object
675 Dim sOutputFormat As String, iTemplate As Integer, iOutputFile As Integer, bOutput As Boolean, sSuffix As String
677 If pvObjectType = acOutputArray Then
680 'Find applicable table or query
681 If pvObjectType = acOutputTable Then Set oTable = TableDefs(pvObjectName, True) Else Set oTable = Querydefs(pvObjectName, True)
682 If IsNull(oTable) Then Goto Error_NotFound
685 'Determine format and parameters
686 If pvOutputFormat =
"" Then
687 sOutputFormat = _PromptFormat(Array(
"HTML
",
"ODS
",
"XLS
",
"XLSX
",
"TXT
"))
' Prompt user for format
688 If sOutputFormat =
"" Then Goto Exit_Function
690 sOutputFormat = UCase(pvOutputFormat)
693 'Determine output file
694 If pvOutputFile =
"" Then
' Prompt file picker to user
695 Select Case sOutputFormat
696 Case UCase(acFormatHTML),
"HTML
" : sSuffix =
"html
"
697 Case UCase(acFormatODS),
"ODS
" : sSuffix =
"ods
"
698 Case UCase(acFormatXLS),
"XLS
" : sSuffix =
"xls
"
699 Case UCase(acFormatXLSX),
"XLSX
" : sSuffix =
"xlsx
"
700 Case UCase(acFormatTXT),
"TXT
",
"CSV
" : sSuffix =
"txt
"
702 sOutputFile = _PromptFilePicker(sSuffix)
703 If sOutputFile =
"" Then Goto Exit_Function
705 sOutputFile = pvOutputFile
707 sOutputFile = ConvertToURL(sOutputFile)
710 Select Case sOutputFormat
711 Case UCase(acFormatHTML),
"HTML
"
712 If pvObjectType = acOutputArray Then
713 bOutput = _OutputToHTML(Nothing, pvObjectName, sOutputFile, pvTemplateFile, pvHeaders, pvData)
715 bOutput = _OutputToHTML(oTable, pvObjectName, sOutputFile, pvTemplateFile)
717 Case UCase(acFormatODS),
"ODS
"
718 bOutput = _OutputToCalc(oTable, sOutputFile, acFormatODS)
719 Case UCase(acFormatXLS),
"XLS
"
720 bOutput = _OutputToCalc(oTable, sOutputFile, acFormatXLS)
721 Case UCase(acFormatXLS),
"XLSX
"
722 bOutput = _OutputToCalc(oTable, sOutputFile, acFormatXLSX)
723 Case UCase(acFormatTXT),
"TXT
",
"CSV
"
724 bOutput = _OutputToCalc(oTable, sOutputFile, acFormatTXT, pvEncoding)
727 'Launch application, if requested
729 If pvAutoStart Then Call _ShellExecute(sOutputFile)
737 If Not IsNull(oTable) Then
741 Utils._ResetCalledSub(cstThisSub)
744 TraceError(TRACEFATAL, ERROBJECTNOTFOUND, Utils._CalledSub(),
0, , Array(_GetLabel(
"OBJECT
"), pvObjectName))
747 TraceError(TRACEABORT, Err, cstThisSub, Erl)
750 TraceError(TRACEFATAL, ERRFILENOTCREATED, Utils._CalledSub(),
0, , sOutputFile)
752 End Function
' OutputTo V1.4
.0
754 REM -----------------------------------------------------------------------------------------------------------------------
755 Public Function Properties(ByVal Optional pvIndex As Variant) As Variant
757 ' a Collection object if pvIndex absent
758 ' a Property object otherwise
760 Utils._SetCalledSub(
"Database.Properties
")
761 Dim vProperty As Variant, vPropertiesList() As Variant, sObject As String
762 vPropertiesList = _PropertiesList()
763 sObject = Utils._PCase(_Type)
764 If IsMissing(pvIndex) Then
765 vProperty = PropertiesGet._Properties(sObject,
"", vPropertiesList)
767 vProperty = PropertiesGet._Properties(sObject,
"", vPropertiesList, pvIndex)
768 vProperty._Value = _PropertyGet(vPropertiesList(pvIndex))
770 Set vProperty._ParentDatabase = _This
773 Set Properties = vProperty
774 Utils._ResetCalledSub(
"Database.Properties
")
776 End Function
' Properties
778 REM -----------------------------------------------------------------------------------------------------------------------
779 Public Function QueryDefs(ByVal Optional pvIndex As Variant, ByVal Optional pbCheck As Boolean) As Object
780 ' Collect all Queries in the database
781 ' pbCheck unpublished
783 If _ErrorHandler() Then On Local Error Goto Error_Function
784 Utils._SetCalledSub(
"Database.QueryDefs
")
785 If IsMissing(pbCheck) Then pbCheck = False
787 Dim sObjects() As String, sObjectName As String, oObject As Object
788 Dim i As Integer, bFound As Boolean, oQueries As Object
789 Set oObject = Nothing
790 If Not IsMissing(pvIndex) Then
791 If Not Utils._CheckArgument(pvIndex,
1, Utils._AddNumeric(vbString)) Then Goto Exit_Function
794 Set oQueries = Connection.getQueries
795 sObjects = oQueries.ElementNames()
797 Case IsMissing(pvIndex)
798 Set oObject = New Collect
799 oObject._CollType = COLLQUERYDEFS
800 oObject._ParentType = OBJDATABASE
801 oObject._ParentName =
""
802 Set oObject._ParentDatabase = _This
803 oObject._Count = UBound(sObjects) +
1
805 Case VarType(pvIndex) = vbString
807 ' Check existence of object and find its exact (case-sensitive) name
808 For i =
0 To UBound(sObjects)
809 If UCase(pvIndex) = UCase(sObjects(i)) Then
810 sObjectName = sObjects(i)
815 If Not bFound Then Goto Trace_NotFound
816 Case Else
' pvIndex is numeric
817 If pvIndex
< 0 Or pvIndex
> UBound(sObjects) Then Goto Trace_IndexError
818 sObjectName = sObjects(pvIndex)
821 Set oObject = New DataDef
822 oObject._Type = OBJQUERYDEF
823 oObject._Name = sObjectName
824 Set oObject._ParentDatabase = _This
825 oObject._readOnly = _ReadOnly
826 Set oObject.Query = oQueries.getByName(sObjectName)
829 Set QueryDefs = oObject
830 Set oObject = Nothing
831 Utils._ResetCalledSub(
"Database.QueryDefs
")
834 TraceError(TRACEABORT, Err,
"Database.QueryDefs
", Erl)
837 If Not pbCheck Then TraceError(TRACEFATAL, ERROBJECTNOTFOUND, Utils._CalledSub(),
0, , Array(_GetLabel(
"QUERY
"), pvIndex))
840 TraceError(TRACEFATAL, ERRCOLLECTION, Utils._CalledSub(),
0)
842 End Function
' QueryDefs V1.1
.0
844 REM -----------------------------------------------------------------------------------------------------------------------
845 Public Function Recordsets(ByVal Optional pvIndex As Variant) As Object
846 ' Collect all active recordsets
848 If _ErrorHandler() Then On Local Error Goto Error_Function
849 Utils._SetCalledSub(
"Database.Recordsets
")
851 Set Recordsets = Nothing
852 If Not IsMissing(pvIndex) Then
853 If Not Utils._CheckArgument(pvIndex,
1, Utils._AddNumeric(vbString)) Then Goto Exit_Function
856 Dim sObjects() As String, sObjectName As String, oObject As Object
857 Dim i As Integer, bFound As Boolean, oTables As Object
860 Case IsMissing(pvIndex)
861 Set oObject = New Collect
862 oObject._CollType = COLLRECORDSETS
863 oObject._ParentType = OBJDATABASE
864 oObject._ParentName =
""
865 Set oObject._ParentDatabase = _This
866 oObject._Count = RecordsetsColl.Count
867 Case VarType(pvIndex) = vbString
868 bFound = _hasRecordset(pvIndex)
869 If Not bFound Then Goto Trace_NotFound
870 Set oObject = RecordsetsColl.Item(pvIndex)
871 Case Else
' pvIndex is numeric
872 If pvIndex
< 0 Or pvIndex
>= RecordsetsColl.Count Then Goto Trace_IndexError
873 Set oObject = RecordsetsColl.Item(pvIndex +
1)
' Collection members are numbered
1 ... Count
877 Set Recordsets = oObject
878 Set oObject = Nothing
879 Utils._ResetCalledSub(
"Database.Recordsets
")
882 TraceError(TRACEABORT, Err,
"Database.Recordsets
", Erl)
885 TraceError(TRACEFATAL, ERROBJECTNOTFOUND, Utils._CalledSub(),
0, , Array(_GetLabel(
"RECORDSET
"), pvIndex))
888 TraceError(TRACEFATAL, ERRCOLLECTION, Utils._CalledSub(),
0)
890 End Function
' Recordsets V0.9
.5
892 REM -----------------------------------------------------------------------------------------------------------------------
893 Public Function RunSQL(Optional ByVal pvSQL As Variant _
894 , Optional ByVal pvOption As Variant _
896 ' Return True if the execution of the SQL statement was successful
897 ' SQL must contain an ACTION query
899 If _ErrorHandler() Then On Local Error Goto Error_Function
901 Utils._SetCalledSub(
"RunSQL
")
904 If IsMissing(pvSQL) Then Call _TraceArguments()
905 If Not Utils._CheckArgument(pvSQL,
1, vbString) Then Goto Exit_Function
907 If IsMissing(pvOption) Then
910 If Not Utils._CheckArgument(pvOption,
2, Utils._AddNumeric(), Array(cstNull, dbSQLPassThrough)) Then Goto Exit_Function
913 Dim oStatement As Object, vResult As Variant
914 Set oStatement = Connection.createStatement()
915 oStatement.EscapeProcessing = Not ( pvOption = dbSQLPassThrough )
916 On Local Error Goto SQL_Error
917 vResult = oStatement.executeUpdate(_ReplaceSquareBrackets(pvSQL))
918 On Local Error Goto Error_Function
924 TraceError(TRACEABORT, Err,
"RunSQL
", Erl)
927 TraceError(TRACEFATAL, ERRSQLSTATEMENT, Utils._CalledSub(),
0, , pvSQL)
929 End Function
' RunSQL V1.1
.0
931 REM -----------------------------------------------------------------------------------------------------------------------
932 Public Function TableDefs(ByVal Optional pvIndex As Variant, ByVal Optional pbCheck As Boolean) As Object
933 ' Collect all tables in the database
934 ' pbCheck unpublished
936 Const cstThisSub =
"Database.TableDefs
"
937 If _ErrorHandler() Then On Local Error Goto Error_Function
938 Utils._SetCalledSub(cstThisSub)
939 If IsMissing(pbCheck) Then pbCheck = False
941 Dim sObjects() As String, sObjectName As String, oObject As Object
942 Dim i As Integer, bFound As Boolean, oTables As Object
943 Set oObject = Nothing
944 If Not IsMissing(pvIndex) Then
945 If Not Utils._CheckArgument(pvIndex,
1, Utils._AddNumeric(vbString)) Then Goto Exit_Function
948 Set oTables = Connection.getTables
949 sObjects = oTables.ElementNames()
951 Case IsMissing(pvIndex)
952 Set oObject = New Collect
953 oObject._CollType = COLLTABLEDEFS
954 oObject._ParentType = OBJDATABASE
955 oObject._ParentName =
""
956 Set oObject._ParentDatabase = _This
957 oObject._Count = UBound(sObjects) +
1
959 Case VarType(pvIndex) = vbString
961 ' Check existence of object and find its exact (case-sensitive) name
962 For i =
0 To UBound(sObjects)
963 If UCase(pvIndex) = UCase(sObjects(i)) Then
964 sObjectName = sObjects(i)
969 If Not bFound Then Goto Trace_NotFound
970 Case Else
' pvIndex is numeric
971 If pvIndex
< 0 Or pvIndex
> UBound(sObjects) Then Goto Trace_IndexError
972 sObjectName = sObjects(pvIndex)
975 Set oObject = New DataDef
979 Set ._ParentDatabase = _This
980 ._ReadOnly = _ReadOnly
981 Set .Table = oTables.getByName(sObjectName)
982 .CatalogName = .Table.CatalogName
983 .SchemaName = .Table.SchemaName
984 .TableName = .Table.Name
988 Set TableDefs = oObject
989 Set oObject = Nothing
990 Utils._ResetCalledSub(cstThisSub)
993 TraceError(TRACEABORT, Err, cstThisSub, Erl)
996 If Not pbCheck Then TraceError(TRACEFATAL, ERROBJECTNOTFOUND, Utils._CalledSub(),
0, , Array(_GetLabel(
"TABLE
"), pvIndex))
999 TraceError(TRACEFATAL, ERRCOLLECTION, Utils._CalledSub(),
0)
1001 End Function
' TableDefs V1.1
.0
1003 REM -----------------------------------------------------------------------------------------------------------------------
1004 REM --- PRIVATE FUNCTIONS ---
1005 REM -----------------------------------------------------------------------------------------------------------------------
1007 REM -----------------------------------------------------------------------------------------------------------------------
1008 Private Function _DFunction(ByVal psFunction As String _
1009 , ByVal psExpr As String _
1010 , ByVal psDomain As String _
1011 , ByVal pvCriteria As Variant _
1012 , ByVal Optional pvOrderClause As Variant _
1014 'Arguments: psFunction an optional aggregate function
1015 ' psExpr: an SQL expression [might contain an aggregate function]
1016 ' psDomain: a table- or queryname
1017 ' pvCriteria: an optional WHERE clause
1018 ' pcOrderClause: an optional order clause incl.
"DESC
" if relevant
1020 If _ErrorHandler() Then On Local Error GoTo Error_Function
1022 Dim oResult As Object
'To retrieve the value to find.
1023 Dim vResult As Variant
'Return value for function.
1024 Dim sSql As String
'SQL statement.
1025 Dim oStatement As Object
'For CreateStatement method
1026 Dim sExpr As String
'For inclusion of aggregate function
1027 Dim sTempField As String
'Random temporary field in SQL expression
1029 Dim sTarget as String, sWhere As String, sOrderBy As String, sLimit As String
1034 sTempField =
"[TEMP
" & Right(
"00000" & Int(
100000 * Rnd),
5)
& "]
"
1035 If pvCriteria
<> "" Then sWhere =
" WHERE
" & pvCriteria Else sWhere =
""
1036 If pvOrderClause
<> "" Then sOrderBy =
" ORDER BY
" & pvOrderClause Else sOrderBy =
""
1037 sLimit =
""
1039 Select Case UCase(MetaData.getDatabaseProductName())
1040 Case
"MYSQL
",
"SQLITE
"
1041 If psFunction =
"" Then
1043 sLimit =
" LIMIT
1"
1045 sTarget = UCase(psFunction)
& "(
" & psExpr
& ")
"
1047 sSql =
"SELECT
" & sTarget
& " AS
" & sTempField
& " FROM
" & psDomain
& sWhere
& sOrderBy
& sLimit
1048 Case Else
' Standard syntax - Includes HSQLDB
1049 If psFunction =
"" Then sTarget =
"TOP
1 " & psExpr Else sTarget = UCase(psFunction)
& "(
" & psExpr
& ")
"
1050 sSql =
"SELECT
" & sTarget
& " AS
" & sTempField
& " FROM
" & psDomain
& sWhere
& sOrderBy
1053 'Lookup the value.
1054 Set oStatement = Connection.createStatement()
1056 .ResultSetType = com.sun.star.sdbc.ResultSetType.FORWARD_ONLY
1057 .ResultSetConcurrency = com.sun.star.sdbc.ResultSetConcurrency.READ_ONLY
1058 .EscapeProcessing = False
1059 sSql = _ReplaceSquareBrackets(sSql)
'Substitute [] by quote string
1060 Set oResult = .executeQuery(sSql)
1061 If Not IsNull(oResult) And Not IsEmpty(oResult) Then
1062 If Not oResult.next() Then Goto Exit_Function
1063 vResult = Utils._getResultSetColumnValue(oResult,
1, True)
' Force return of binary field
1068 'Assign the returned value.
1069 _DFunction = vResult
1070 Set oResult = Nothing
1071 Set oStatement = Nothing
1074 TraceError(TRACEABORT, ERRDFUNCTION, _A2B_.CalledSub,
0, , sSQL)
1076 End Function
' DFunction V1.5
.0
1078 REM -----------------------------------------------------------------------------------------------------------------------
1079 Private Function _FilterOptionsDefault(ByVal plEncoding As Long) As String
1080 ' Return the default FilterOptions string for table/query export to csv
1082 Dim sFieldSeparator as string
1083 Const cstComma =
",
"
1084 Const cstTextDelimitor =
""""
1086 If _DecimalPoint() =
",
" Then sFieldSeparator =
";
" Else sFieldSeparator = cstComma
1087 _FilteroptionsDefault = Trim(Str(Asc(sFieldSeparator))) _
1088 & cstComma
& Trim(Str(Asc(cstTextDelimitor))) _
1089 & cstComma
& Trim(Str(plEncoding)) _
1090 & cstComma
& "1"
1092 End Function
' _FilterOptionsDefault V1.4
.0
1094 REM -----------------------------------------------------------------------------------------------------------------------
1095 Public Function _hasRecordset(ByVal psName As String) As Boolean
1096 ' Return True if psName if in the collection of Recordsets
1098 Dim oRecordset As Object
1099 If _ErrorHandler() Then On Local Error Goto Error_Function
1100 Set oRecordset = RecordsetsColl.Item(psName)
1101 _hasRecordset = True
1105 Error_Function:
' Item by key aborted
1106 _hasRecordset = False
1108 End Function
' _hasRecordset V0.9
.5
1110 REM -----------------------------------------------------------------------------------------------------------------------
1111 Private Sub _LoadMetadata()
1112 ' Load essentially getTypeInfo() results from Metadata
1114 Dim sProduct As String
1115 Dim iInfo As Integer, oTypeInfo As Object, sName As String, lType As Integer
1117 Const cstMaxInfo =
40
1118 ReDim _ColumnTypes(
0 To cstMaxInfo)
1119 ReDim _ColumnTypeNames(
0 To cstMaxInfo)
1120 ReDim _ColumnPrecisions(
0 To cstMaxInfo)
1121 Const cstHSQLDB1 =
"HSQL Database Engine
1.
"
1122 Const cstHSQLDB2 =
"HSQL Database Engine
2.
"
1123 Const cstMSAccess2003 =
"MS Jet
0"
1124 Const cstMSAccess2007 =
"MS Jet
04.
"
1125 Const cstMYSQL =
"MySQL
"
1126 Const cstPOSTGRES =
"PostgreSQL
"
1127 Const cstSQLITE =
"SQLite
"
1129 With com.sun.star.sdbc.DataType
1130 _ColumnTypesReference = Array( _
1164 sProduct = .getDatabaseProductName()
& " " & .getDatabaseProductVersion
1166 Case Len(sProduct)
> Len(cstHSQLDB1) And Left(sProduct, Len(cstHSQLDB1)) = cstHSQLDB1
1167 _RDBMS = DBMS_HSQLDB1
1168 _ColumnTypesAlias = Array(
0, -
5, -
2,
16, -
4,
16,
1, -
1,
91,
3,
0,
8,
6,
4, -
4, -
1,
2,
0,
0,
7,
0,
5,
0,
0,
92,
93, -
6, -
3,
12)
1169 _BinaryStream = True
1170 Case Len(sProduct)
> Len(cstHSQLDB2) And Left(sProduct, Len(cstHSQLDB2)) = cstHSQLDB2
1171 _RDBMS = DBMS_HSQLDB2
1172 _ColumnTypesAlias = Array(
0, -
5, -
3, -
7,
2004,
16,
1,
2005,
91,
3,
0,
8,
8,
4, -
3,
12,
2,
0,
0,
8,
0,
5,
0,
0,
92,
93, -
6, -
3,
12)
1173 _BinaryStream = True
1174 Case Len(sProduct)
> Len(cstMSAccess2007) And Left(sProduct, Len(cstMSAccess2007)) = cstMSAccess2007
1175 _RDBMS = DBMS_MSACCESS2007
1176 _ColumnTypesAlias = Array(
0,
4, -
2,
16, -
2,
16,
12,
12,
93,
8,
0,
8,
6,
4, -
3,
12,
2,
0,
0,
8,
0,
5,
0,
0,
93,
93, -
6, -
2,
12)
1177 _BinaryStream = True
1178 Case Len(sProduct)
> Len(cstMSAccess2003) And Left(sProduct, Len(cstMSAccess2003)) = cstMSAccess2003
1179 _RDBMS = DBMS_MSACCESS2003
1180 _ColumnTypesAlias = Array(
0,
4, -
2,
16, -
2,
16,
12,
12,
93,
8,
0,
8,
6,
4, -
3,
12,
2,
0,
0,
8,
0,
5,
0,
0,
93,
93, -
6, -
2,
12)
1181 _BinaryStream = True
1182 Case Len(sProduct)
> Len(cstMYSQL) And Left(sProduct, Len(cstMYSQL)) = cstMYSQL
1184 _ColumnTypesAlias = Array(
0, -
5, -
2, -
7, -
4, -
7,
1, -
1,
91,
3,
0,
8,
8,
4, -
4, -
1,
2,
0,
0,
7,
0,
5,
0,
0,
92,
93, -
6, -
3, -
1)
1185 _BinaryStream = False
1186 Case Len(sProduct)
> Len(cstPOSTGRES) And Left(sProduct, Len(cstPOSTGRES)) = cstPOSTGRES
1187 _RDBMS = DBMS_POSTGRES
1188 _ColumnTypesAlias = Array(
0, -
5, -
3,
16, -
3,
16,
1,
12,
91,
8,
0,
8,
8,
4, -
3,
12,
2,
0,
0,
7,
0,
5,
0,
0,
92,
93,
4, -
3,
12)
1189 _BinaryStream = True
1190 Case Len(sProduct)
> Len(cstSQLITE) And Left(sProduct, Len(cstSQLITE)) = cstSQLITE
1191 _RDBMS = DBMS_SQLITE
1192 _ColumnTypesAlias = Array(
0, -
5, -
4, -
7, -
4, -
7,
1, -
1,
91,
8,
0,
8,
6,
4, -
4, -
1,
8,
0,
0,
8,
0,
5,
0,
0,
92,
93, -
6, -
4,
12)
1193 _BinaryStream = True
1194 Case Else
' Firebird TODO
1195 _RDBMS = DBMS_UNKNOWN
1196 _BinaryStream = True
1200 Set oTypeInfo = MetaData.getTypeInfo()
1203 Do While Not .isAfterLast() And iInfo
< cstMaxInfo
1204 sName = .getString(
1)
1206 If _RDBMS = DBMS_POSTGRES And (Left(sName,
1)
<> "_
" Or lType
<> -
1) Then
' Skip
1209 _ColumnTypeNames(iInfo) = sName
1210 _ColumnTypes(iInfo) = lType
1211 _ColumnPrecisions(iInfo) = .getLong(
3)
1216 ReDim Preserve _ColumnTypes(
0 To iInfo)
1217 ReDim Preserve _ColumnTypeNames(
0 To iInfo)
1218 ReDim Preserve _ColumnPrecisions(
0 To iInfo)
1221 End Sub
' _LoadMetadata V1.6
.0
1223 REM -----------------------------------------------------------------------------------------------------------------------
1224 Private Function _OutputBooleanToHTML(ByVal pbBool As Boolean) As String
1225 ' Converts input boolean value to HTML compatible string
1227 _OutputBooleanToHTML = Iif(pbBool,
"&#
9745;
",
"&#
9746;
")
1229 End Function
' _OutputBooleanToHTML V1.4
.0
1231 REM -----------------------------------------------------------------------------------------------------------------------
1232 Private Function _OutputClassToHTML(ByVal pvArray As variant) As String
1233 ' Formats classes attribute of
<tr
> and
<td
> tags
1235 If Not IsArray(pvArray) Then
1236 _OutputClassToHTML =
""
1237 ElseIf UBound(pvArray)
< LBound(pvArray) Then
1238 _OutputClassToHTML =
""
1240 _OutputClassToHTML =
" class=
""" & Join(pvArray,
" ")
& """"
1243 End Function
' _OutputClassToHTML V1.4
.0
1245 REM -----------------------------------------------------------------------------------------------------------------------
1246 Private Function _OutputDataToHTML(ByRef pvTable As Variant, ByVal pvName As String, ByVal piFile As Integer _
1247 , ByRef Optional pvHeaders As Variant _
1248 , ByRef Optional pvData As Variant _
1250 ' Write html tags around data found in pvTable
1251 ' Exit when error without execution stop (to avoid file remaining open ...)
1253 Dim oTableRS As Object, vData() As Variant, i As Integer, j As Integer
1254 Dim vFieldsBin() As Variant, iDataType As Integer, iNumRows As Integer, iNumFields As Integer, vDataCell As Variant
1255 Dim bDataArray As Boolean, sHeader As String
1256 Dim vTrClass() As Variant, vTdClass As Variant, iCountRows As Integer, iLastRow As Integer
1257 Const cstMaxRows =
200
1258 On Local Error GoTo Error_Function
1260 bDataArray = IsNull(pvTable)
1261 Print #piFile,
" <table class=
""dbdatatable
"">"
1262 Print #piFile,
" <caption
>" & pvName
& "</caption
>"
1264 vFieldsBin() = Array()
1266 Set oTableRS = Nothing
1267 iNumFields = UBound(pvHeaders) +
1
1268 ReDim vFieldsBin(
0 To iNumFields -
1)
1269 For i =
0 To iNumFields -
1
1270 vFieldsBin(i) = False
1273 Set oTableRS = pvTable.OpenRecordset( , , dbReadOnly)
1274 iNumFields = oTableRS.Fields.Count
1275 ReDim vFieldsBin(
0 To iNumFields -
1)
1276 With com.sun.star.sdbc.DataType
1277 For i =
0 To iNumFields -
1
1278 iDataType = oTableRS.Fields(i).DataType
1279 vFieldsBin(i) = Utils._IsBinaryType(iDataType)
1285 Print #piFile,
" <thead
>"
1286 Print #piFile,
" <tr
>"
1287 For i =
0 To iNumFields -
1
1288 If bDataArray Then sHeader = pvHeaders(i) Else sHeader = .Fields(i)._Name
1289 Print #piFile,
" <th scope=
""col
"">" & sHeader
& "</th
>"
1291 Print #piFile,
" </tr
>"
1292 Print #piFile,
" </thead
>"
1293 Print #piFile,
" <tfoot
>"
1294 Print #piFile,
" </tfoot
>"
1296 Print #piFile,
" <tbody
>"
1298 iLastRow = UBound(pvData,
2) +
1
1301 iLastRow = .RecordCount
1305 Do While iCountRows
< iLastRow
1309 vData() = .GetRows(cstMaxRows)
1310 iNumRows = UBound(vData,
2) +
1
1312 For j =
0 To iNumRows -
1
1313 iCountRows = iCountRows +
1
1314 vTrClass() = Array()
1315 If iCountRows =
1 Then vTrClass() = _AddArray(vTrClass,
"firstrow
")
1316 If iCountRows = iLastRow Then vTrClass() = _AddArray(vTrClass,
"lastrow
")
1317 If (iCountRows Mod
2) =
0 Then vTrClass() = _AddArray(vTrClass,
"even
") Else vTrClass() = _AddArray(vTrClass,
"odd
")
1318 Print #piFile,
" <tr
" & _OutputClassToHTML(vTrClass)
& ">"
1319 For i =
0 To iNumFields -
1
1320 vTdClass() = Array()
1321 If i =
0 Then vTdClass() = _AddArray(vTdClass,
"firstcol
")
1322 If i = iNumFields -
1 Then vTdClass() = _AddArray(vTdClass,
"lastcol
")
1323 If Not vFieldsBin(i) Then
1324 If bDataArray Then vDataCell = pvData(i, j) Else vDataCell = vData(i, j)
1325 Select Case VarType(vDataCell)
1326 Case vbEmpty, vbNull
1327 vTdClass() = _AddArray(vTdClass,
"null
")
1328 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputNullToHTML()
& "</td
>"
1329 Case vbInteger, vbLong, vbSingle, vbDouble, vbCurrency, vbDecimal, vbUShort, vbULong, vbBigInt
1330 vTdClass() = _AddArray(vTdClass,
"numeric
")
1331 If vDataCell
< 0 Then vTdClass() = _AddArray(vTdClass,
"negative
")
1332 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputNumberToHTML(vDataCell)
& "</td
>"
1334 vTdClass() = _AddArray(vTdClass,
"bool
")
1335 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputBooleanToHTML(vDataCell)
& "</td
>"
1337 vTdClass() = _AddArray(vTdClass,
"date
")
1338 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputDateToHTML(vDataCell)
& "</td
>"
1340 vTdClass() = _AddArray(vTdClass,
"char
")
1341 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputStringToHTML(vDataCell)
& "</td
>"
1343 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _CStr(vDataCell)
& "</td
>"
1345 Else
' Binary fields
1346 Print #piFile,
" <td
" & _OutputClassToHTML(vTdClass)
& ">" & _OutputBinaryToHTML()
& "</td
>"
1349 Print #piFile,
" </tr
>"
1353 If Not bDataArray Then .mClose()
1355 Set oTableRS = Nothing
1357 Print #piFile,
" </tbody
>"
1358 Print #piFile,
" </table
>"
1359 _OutputDataToHTML = True
1364 TraceError(TRACEWARNING, Err,
"_OutputDataToHTML
", Erl)
1365 _OutputDataToHTML = False
1366 Resume Exit_Function
1367 End Function
' _OutputDataToHTML V1.4
.0
1369 REM -----------------------------------------------------------------------------------------------------------------------
1370 Private Function _OutputBinaryToHTML() As String
1371 ' Converts Binary value to HTML compatible string
1373 _OutputBinaryToHTML =
"&nbsp;
"
1375 End Function
' _OutputBinaryToHTML V1.4
.0
1377 REM -----------------------------------------------------------------------------------------------------------------------
1378 Private Function _OutputDateToHTML(ByVal psDate As Date) As String
1379 ' Converts input date to HTML compatible string
1381 _OutputDateToHTML = Format(psDate)
' With regional settings - Ignores time if = to
0
1383 End Function
' _OutputDateToHTML V1.4
.0
1385 REM -----------------------------------------------------------------------------------------------------------------------
1386 Private Function _OutputNullToHTML() As String
1387 ' Converts Null value to HTML compatible string
1389 _OutputNullToHTML =
"&nbsp;
"
1391 End Function
' _OutputNullToHTML V1.4
.0
1393 REM -----------------------------------------------------------------------------------------------------------------------
1394 Private Function _OutputNumberToHTML(ByVal pvNumber As Variant, ByVal Optional piPrecision As Integer) As String
1395 ' Converts input number to HTML compatible string
1397 Dim vNumber As Variant
1398 If IsMissing(piPrecision) Then piPrecision = -
1
1399 If pvNumber = Int(pvNumber) Then
1400 vNumber = Int(pvNumber)
1402 If piPrecision
>=
0 Then vNumber = (Int(pvNumber *
10 ^ piPrecision +
0.5)) /
10 ^ piPrecision Else vNumber = pvNumber
1404 _OutputNumberToHTML = Format(vNumber)
1406 End Function
' _OutputNumberToHTML V1.4
.0
1408 REM -----------------------------------------------------------------------------------------------------------------------
1409 Private Function _OutputStringToHTML(ByVal psString As String) As String
1410 ' Converts input string to HTML compatible string
1411 ' - UTF-
8 encoding
1412 ' - recognition of next patterns
1413 ' -
&quot; -
&amp; -
&apos; -
&lt; -
&gt;
1414 ' -
<pre
>
1415 ' -
<a href=
"...
1417 ' -
<img src=
"...
1418 ' -
<b
>,
<u
>,
<i
>
1420 Dim vPatterns As Variant
1421 Dim lCurrentChar as Long, lPattern As Long, lNextPattern As Long, sPattern As String
1422 Dim sOutput As String, sChar As String
1423 Dim sUrl As String, lNextQuote As Long, lUrl As Long, bQuote As Boolean, bTagEnd As Boolean
1424 Dim i As Integer, l As Long
1426 vPatterns = Array( _
1427 "&quot;
",
"&amp;
",
"&apos;
",
"&lt;
",
"&gt;
",
"&nbsp;
" _
1428 ,
"<pre
>",
"</pre
>",
"<br
>" _
1429 ,
"<a href=
""",
"<a id=
""",
"</a
>",
"<img src=
""" _
1430 ,
"<span style=
""",
"</span
>" _
1431 ,
"<b
>",
"</b
>",
"<u
>",
"</u
>",
"<i
>",
"</i
>" _
1435 sOutput =
""
1437 Do While lCurrentChar
<= Len(psString)
1438 ' Where is next closest pattern ?
1439 lPattern = Len(psString) +
1
1440 sPattern =
""
1441 For i =
0 To UBound(vPatterns)
1442 lNextPattern = InStr(lCurrentChar, psString, vPatterns(i),
1)
' Text (not case-sensitive) string comparison
1443 If lNextPattern
> 0 And lNextPattern
< lPattern Then
1444 lPattern = lNextPattern
1445 sPattern = Mid(psString, lPattern, Len(vPatterns(i)))
1448 ' Up to the next pattern or to the end of the string, UTF8-encode each character
1449 For l = lCurrentChar To lPattern -
1
1450 sChar = Mid(psString, l,
1)
1451 sOutput = sOutput
& Utils._UTF8Encode(sChar)
1453 ' Process hyperlink patterns and keep others
1454 If Len(sPattern)
> 0 Then
1455 Select Case LCase(sPattern)
1456 Case
"<a href=
""",
"<a id=
""",
"<img src=
""",
"<span style=
"""
1457 ' Up to next quote, url-encode
1459 lUrl = lPattern + Len(sPattern)
1460 lNextQuote = InStr(lUrl, psString,
"""",
1)
1461 If lNextQuote =
0 Then lNextQuote = Len(psString)
' Should not happen but, if quoted string not closed ...
1462 sUrl = Mid(psString, lUrl, lNextQuote - lUrl)
1463 sOutput = sOutput
& sPattern
& Iif(sPattern =
"<a id=
""", sUrl, ConvertToUrl(sUrl))
& """"
1464 lCurrentChar = lNextQuote +
1
1468 sChar = Mid(psString, lCurrentChar,
1)
1470 Case
""""
1472 sOutput = sOutput
& sChar
1473 Case
">" ' Tag end if not somewhere between quotes
1476 sOutput = sOutput
& sChar
1478 sOutput = sOutput
& _UTF8Encode(sChar)
1481 sOutput = sOutput
& _UTF8Encode(sChar)
1483 lCurrentChar = lCurrentChar +
1
1484 If lCurrentChar
> Len(psString) Then bTagEnd = True
' Should not happen but, if tag not closed ...
1487 sOutput = sOutput
& sPattern
1488 lCurrentChar = lPattern + Len(sPattern)
1491 lCurrentChar = Len(psString) +
1
1495 _OutputStringToHTML = sOutput
1497 End Function
' _OutputStringToHTML V1.4
.0
1499 REM -----------------------------------------------------------------------------------------------------------------------
1500 Private Function _OutputToCalc(poData As Object _
1501 , ByVal psOutputFile As String _
1502 , ByVal psFilter As String _
1503 , Optional ByVal plEncoding As Long _
1505 ' https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Database_Import
1506 ' https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options
1508 Dim oCalcDoc As Object, oSheet As Object, vWin As Variant
1509 Dim vImportDesc() As Variant, iSource As Integer
1510 Dim oRange As Object, i As Integer, iCol As Integer, oColumns As Object
1512 If _ErrorHandler() Then On Local Error Goto Error_Function
1513 _OutputToCalc = False
1514 If IsMissing(plEncoding) Then plEncoding = acUTF8Encoding
1515 ' Create a new OO-Calc-Document
1516 Set oCalcDoc = StarDesktop.LoadComponentFromURL( _
1517 "private:factory/scalc
" _
1518 ,
"_default
" ,
0, Array() _
1521 ' Get the unique spreadsheet
1522 Set oSheet = oCalcDoc.Sheets(
0)
1524 ' Describe import
1526 If ._Type =
"TABLEDEF
" Then
1527 iSource = com.sun.star.sheet.DataImportMode.TABLE
1529 iSource = com.sun.star.sheet.DataImportMode.QUERY
1531 vImportDesc = Array( _
1532 _MakePropertyValue(
"DatabaseName
", URL) _
1533 , _MakePropertyValue(
"SourceType
", iSource) _
1534 , _MakePropertyValue(
"SourceObject
", ._Name) _
1536 oSheet.Name = ._Name
1540 oSheet.getCellByPosition(
0,
0).doImport(vImportDesc())
1542 Select Case psFilter
1543 Case acFormatODS, acFormatXLS, acFormatXLSX
' Formatting
1544 iCol = poData.Fields().Count
1545 Set oRange = oSheet.getCellRangeByPosition(
0,
0, iCol -
1,
0)
1546 oRange.CharWeight = com.sun.star.awt.FontWeight.BOLD
1547 oRange.CellBackColor = RGB(
200,
200,
200)
1548 oRange.HoriJustify = com.sun.star.table.CellHoriJustify.CENTER
1549 Set oColumns = oRange.getColumns()
1550 For i =
0 To iCol -
1
1551 oColumns.getByIndex(i).OptimalWidth = True
1553 oCalcDoc.storeAsUrl(psOutputFile, Array( _
1554 _MakePropertyValue(
"FilterName
", psFilter) _
1555 , _MakePropertyValue(
"Overwrite
", True) _
1558 oCalcDoc.storeAsUrl(psOutputFile, Array( _
1559 _MakePropertyValue(
"FilterName
", psFilter) _
1560 , _MakePropertyValue(
"FilterOptions
", _FilterOptionsDefault(plEncoding)) _
1561 , _MakePropertyValue(
"Overwrite
", True) _
1565 oCalcDoc.close(False)
1566 _OutputToCalc = True
1569 Set oColumns = Nothing
1570 Set oRange = Nothing
1571 Set oSheet = Nothing
1572 Set oCalcDoc = Nothing
1575 TraceError(TRACEABORT, ERRDFUNCTION, _A2B_.CalledSub,
0, , sSQL)
1577 End Function
' OutputToCalc V1.4
.0
1579 REM -----------------------------------------------------------------------------------------------------------------------
1580 Public Function _OutputToHTML(ByRef pvTable As Variant, ByVal pvName As String, ByVal psOutputFile As String, ByVal psTemplateFile As String _
1581 , ByRef Optional pvHeaders As Variant _
1582 , ByRef Optional pvData As Variant _
1584 ' http://www.ehow.com/how_5652706_create-html-template-ms-access.html
1586 Dim bDataArray As Boolean
1587 Dim vMinimalTemplate As Variant, vTemplate As Variant
1588 Dim iFile As Integer, i As Integer, sLine As String, lBody As Long
1589 Const cstTitle =
"<!--Template_Title--
>", cstBody =
"<!--Template_Body--
>"
1590 Const cstTitleAlt =
"<!--AccessTemplate_Title--
>", cstBodyAlt =
"<!--AccessTemplate_Body--
>"
1592 On Local Error GoTo Error_Function
1593 vMinimalTemplate = Array( _
1594 "<!DOCTYPE html
>" _
1595 ,
"<html
>" _
1596 ,
" <head
>" _
1597 ,
" <title
>" & cstTitle
& "</title
>" _
1598 ,
" </head
>" _
1599 ,
" <body
>" _
1600 ,
" " & cstBody _
1601 ,
" </body
>" _
1602 ,
"</html
>" _
1605 vTemplate = _ReadFileIntoArray(psTemplateFile)
1606 If LBound(vTemplate)
> UBound(vTemplate) Then vTemplate() = vMinimalTemplate()
1608 bDataArray = IsNull(pvTable)
1610 ' Write output file
1612 Open psOutputFile For Output Access Write Lock Read Write As #iFile
1613 For i =
0 To UBound(vTemplate)
1614 sLine = vTemplate(i)
1615 sLine = Join(Split(sLine, cstTitleAlt), cstTitle)
1616 sLine = Join(Split(sLine, cstBodyAlt), cstBody)
1618 Case InStr(sLine, cstTitle)
> 0
1619 sLine = Join(Split(sLine, cstTitle), pvName)
1621 Case InStr(sLine, cstBody)
> 0
1622 lBody = InStr(sLine, cstBody)
1623 If lBody
> 1 Then Print #iFile, Left(sLine, lBody -
1)
1625 _OutputDataToHTML(pvTable, pvName, iFile, pvHeaders, pvData)
1627 _OutputDataToHTML(pvTable, pvName, iFile)
1629 If Len(sLine)
> lBody + Len(cstBody) -
1 Then Print #iFile, Right(sLine, Len(sLine) - lBody + Len(cstBody) +
1)
1636 _OutputToHTML = True
1641 _OutputToHTML = False
1643 End Function
' _OutputToHTML V1.4
.0
1645 REM -----------------------------------------------------------------------------------------------------------------------
1646 Private Function _PropertiesList() As Variant
1648 _PropertiesList = Array(
"Connect
",
"Name
",
"ObjectType
",
"Version
")
1650 End Function
' _PropertiesList
1652 REM -----------------------------------------------------------------------------------------------------------------------
1653 Private Function _PropertyGet(ByVal psProperty As String) As Variant
1654 ' Return property value of the psProperty property name
1656 If _ErrorHandler() Then On Local Error Goto Error_Function
1657 Utils._SetCalledSub(
"Database.get
" & psProperty)
1658 Dim vEMPTY As Variant
1659 _PropertyGet = vEMPTY
1661 Select Case UCase(psProperty)
1662 Case UCase(
"Connect
")
1663 _PropertyGet = Document.Datasource.URL
1664 ' Location = ConvertFromUrl(URL)
1665 Case UCase(
"Name
")
1666 _PropertyGet = Title
1667 Case UCase(
"ObjectType
")
1668 _PropertyGet = _Type
1669 Case UCase(
"Version
")
1670 _PropertyGet = MetaData.getDatabaseProductName()
& " " & MetaData.getDatabaseProductVersion
1676 Utils._ResetCalledSub(
"Database.get
" & psProperty)
1679 TraceError(TRACEFATAL, ERRPROPERTY, Utils._CalledSub(),
0, , psProperty)
1680 _PropertyGet = vEMPTY
1683 TraceError(TRACEABORT, Err,
"Database._PropertyGet
", Erl)
1684 _PropertyGet = vEMPTY
1686 End Function
' _PropertyGet
1688 REM -----------------------------------------------------------------------------------------------------------------------
1689 Public Function _ReplaceSquareBrackets(ByVal psSql As String) As String
1690 ' Returns psSql after substitution of [] by quote character
1691 ' [] square brackets in (single) quoted strings not affected
1693 Dim sQuote As String
'RDBMS specific quote character
1694 Dim vSubStrings() As Variant, i As Integer
1695 Const cstSingleQuote =
"'"
1697 sQuote = MetaData.IdentifierQuoteString
1698 If sQuote =
" " Then
' IdentifierQuoteString returns a space
" " if identifier quoting is not supported.
1699 _ReplaceSquareBrackets = Trim(psSql)
1702 vSubStrings() = Split(psSql, cstSingleQuote)
1703 For i =
0 To UBound(vSubStrings)
1704 If (i Mod
2) =
0 Then
' Only even substrings are parsed for square brackets
1705 vSubStrings(i) = Join(Split(vSubStrings(i),
"[
"), sQuote)
1706 vSubStrings(i) = Join(Split(vSubStrings(i),
"]
"), sQuote)
1710 _ReplaceSquareBrackets = Trim(Join(vSubStrings, cstSingleQuote))
1712 End Function
' ReplaceSquareBrackets V1.1
.0