Using Databasebackup macro in Base documentation

In a recent post @Ratslinger pointed to an interesting backup macro found in the Base documentation starting on on page 63.

Unfortunately the suggested macro comes with scant documentation on how it works, and one glaring syntax error that further confused me.

Start by correcting the syntax error, from:
...FOR k = 1 TO inMax - 1 TO 1 STEP -1...
to this:
...FOR k = inMax - 1 TO 1 STEP -1....

i.e. you can’t have more than one TO clause in a FOR statement. :wink:


With my comments added to help you understand how it works here is the code from the manual. I found it instructive: Databasebackup.odt

Wide load tip: Cut and paste into your wide screen programmer’s editor. I like: Kate or Notepadqq (linux) or Notepad++ (windows). Set tabs to 4 columns, use fixed width font. These editors allow quick and easy block indenting and out-denting with tabs. I use Kate most of the time but the latest version of Notepadqq allows converting tabs to spaces or the reverse.

Also, sorry, I know .odt isn’t a very good way to transport code between us, but Ask.LibreOffice.org won’t accept other formats, like .txt or .bas, and I can’t paste it below without it messing up line wrapping, for some unknown reason to be addressed another day. Suggestions for how to share code better, but without abandoning tabs or wide code are welcome.

That woks for me:

SUB Databasebackup (inMax AS INTEGER)

DIM oPath AS OBJECT
DIM oDoc AS OBJECT
DIM sTitle AS STRING
DIM sUrl_End AS STRING
DIM sUrl_Start AS STRING
DIM i AS INTEGER
DIM k AS INTEGER
oDoc = ThisComponent
sTitle = oDoc.Title
sUrl_Start = oDoc.URL
	DO WHILE sUrl_Start =""
		oDoc = oDoc.Parent
		sTitle = oDoc.Title
		sUrl_Start = oDoc.URL
	LOOP

	oPath = createUnoService("com.sun.star.util.PathSettings")
	FOR i  = 1 TO inMax +1
		IF NOT FileExists(oPath.Backup & "/" & i & "_" & sTitle) THEN
				IF i > inMax THEN
					FOR k = 1 TO inMax -1 STEP -1
							IF FileDateTime(oPath.Backup & "/" & k & "_" & sTitle) <=  FileDateTime(oPath.Backup & "/" & k+1 & "_" & sTitle) THEN
									IF k=1 THEN
											i=k
											EXIT FOR
									END IF
							ELSE
									i=k+1
									EXIT FOR
							ENDIF
					NEXT
				END IF
				EXIT FOR
		END IF
	NEXT
	sUrl_End = oPath.Backup & "/" & i &"_" & sTitleFileCopy(sUrl_Start,sUrl_End)
END SUB

SUB Write_data_out_of_cache
	DIM oData AS OBJECT
	DIM oDataSource AS OBJECT
	
   if IsNull(Thisdatabasedocument.CurrentController.ActiveConnection) then
    	Thisdatabasedocument.CurrentController.connect
	endif
	
	oData = ThisDatabaseDocument.CurrentController
	IF NOT( oData.isConnected() )THEN oData.connect()
			oDataSource = oData.DataSource
			oDataSource.flush
END SUB

SUB BackupNow
	Write_data_out_of_cache
	DatabaseBackup(10)
END SUB