Question
· Apr 3, 2023

SQL CREATE DATABASE from template

In some testing scenarios, I need to clone the database. While I use only SQL access.

I need all data to be cloned, not mapped from the original database, and a separate database to be accessed.

Is there any way to do so?

Something like

CREATE DATABASE [Database to create]
WITH TEMPLATE [Database to copy]
Discussion (1)1
Log in or sign up to continue

Implemented it with SQL Procedure

CREATE OR REPLACE PROCEDURE %ZDJANGO.CLONE_DATABASE(sourceNS %String, targetNS %String)
LANGUAGE OBJECTSCRIPT
{
	new $namespace
	set $namespace = "%SYS"
	
	$$$ThrowOnError(##class(Config.Namespaces).Get(sourceNS, .sourceNSparams))
	$$$ThrowOnError(##class(Config.Namespaces).Get(targetNS, .targetNSparams))
	
	for kind="Globals", "Routines" {
		$$$ThrowOnError(##class(Config.Databases).Get(sourceNSparams(kind), .sourceDBparams))
		$$$ThrowOnError(##class(Config.Databases).Get(targetNSparams(kind), .targetDBparams))
		
		set from = sourceDBparams("Directory")
		set to = targetDBparams("Directory")
		
		quit:$Data(done(to))
		set done(to) = "" 
		
		$$$ThrowOnError(##class(SYS.Database).Copy(from, to, , , 4))
	}
} 

DANGER: Do not use it, made specifically for my case, it may overwrite database