# svyDeployUtils

The `svyDeployUtils` scope provides utilities for the deployment lifecycle of a Servoy Cloud application. It covers three areas:

* **Database migration** — run versioned SQL scripts at startup to keep your schema up to date
* **Report deployment** — copy Jasper report files from solution media to the server's report directory
* **Database cloning** — create and initialize cloned database server configurations for multi-tenant or test setups

## Database migration

### `runDBVersionUpgrade()`

Runs SQL migration files stored in your solution's media library. Call this during `onSolutionOpen` to ensure the database schema is always at the correct version before the application starts.

```javascript
scopes.svyDeployUtils.runDBVersionUpgrade();
```

| Parameter              | Type     | Default                | Description                                                                                                        |
| ---------------------- | -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `versionTableName`     | `String` | —                      | Table name to store version history. When set, versions are tracked in the database instead of `servoy.properties` |
| `migrationFilesFolder` | `String` | `'database-migration'` | Media folder path containing the SQL files                                                                         |

#### File naming convention

Migration files must follow this exact naming pattern:

```bash
database-migration/${type}__${version}__${ServoyDBName}__${description}.sql
```

* **`${type}`**: `V` for versioned (runs once) or `R` for repeat (runs on every deployment)
* **`${version}`**: A number. Version files execute in ascending order
* **`${ServoyDBName}`**: The Servoy database server name (must match a configured server)
* **`${description}`**: Free text description of what the migration does

{% hint style="warning" %}
The separator is `__` (two underscores), not one. A single underscore will not be parsed correctly and the file will be silently ignored. Every part of the filename must be separated by exactly two underscores.
{% endhint %}

**Examples:**

```bash
database-migration/V__1__my_database__initial_schema.sql
database-migration/V__2__my_database__add_users_table.sql
database-migration/R__1__my_database__refresh_views.sql
```

#### How it works

1. Version files (`V__`) run once in order. Once version 3 has been applied, versions 1 and 2 are never run again.
2. Repeat files (`R__`) run on every deployment, as long as their version number is at or below the current version.
3. If a version file fails, an error is thrown and the upgrade stops.
4. Duplicate version numbers for the same database throw an error before any SQL is executed.
5. After all migrations complete, all database server data models are reloaded automatically.

{% hint style="info" %}
When using `versionTableName`, the table is created automatically on first run if it does not exist yet. In developer mode you must create it manually — the function will tell you the required schema.
{% endhint %}

### `getCurrentVersion(serverName, tableName)`

Returns the current migration version for a given database server.

```javascript
var version = scopes.svyDeployUtils.getCurrentVersion('my_database', 'db_version');
application.output('Current version: ' + version);
```

## Report deployment

### `copyReportsToServer()`

Copies all Jasper report files (`.jrxml` and `.jasper`) from the solution media under the `reports/` path to the Jasper reports directory on the server.

```javascript
scopes.svyDeployUtils.copyReportsToServer();
```

Call this during `onSolutionOpen` so that the report files on disk always match the ones in the solution.

## Reading and writing Servoy and system properties

These functions give you access to different property sources at runtime. Use `getEnvironmentProperty` for Servoy Cloud environment variables, `getServoyProperty` for values in `servoy.properties`, and `getSystemProperty` for JVM-level properties.

### `getServoyProperty(name)`

Returns a value from `servoy.properties`. Compatible with both older and newer Servoy versions.

```javascript
var dbUrl = scopes.svyDeployUtils.getServoyProperty('dataProviderID');
```

### `setServoyProperty(name, newValue)`

Sets a value in `servoy.properties` and saves the file.

```javascript
scopes.svyDeployUtils.setServoyProperty('MY_DATABASE.DB_VERSION', '5');
```

### `getEnvironmentProperty(name)`

Returns an OS environment variable value. Returns `null` if the variable is not set.

```javascript
var env = scopes.svyDeployUtils.getEnvironmentProperty('ENVIRONMENT');
```

### `getSystemProperty(name)`

Returns a Java system property value. Returns `null` if not set.

```javascript
var tmpDir = scopes.svyDeployUtils.getSystemProperty('java.io.tmpdir');
```

## Database cloning

These functions manage Servoy server configurations for cloned (multi-tenant) Postgres databases.

### `createNewCloneOfDatabase(originalDBServoyName, newDBNamePostgres, newDBNameServoyName)`

Creates a new Servoy server configuration that points to a Postgres database that is a clone of an existing one. The clone inherits the JDBC connection settings from the original, with the database name replaced.

| Parameter              | Type                | Description                                                           |
| ---------------------- | ------------------- | --------------------------------------------------------------------- |
| `originalDBServoyName` | `String`            | The existing Servoy server name to clone from                         |
| `newDBNamePostgres`    | `String`            | The actual Postgres database name for the new server                  |
| `newDBNameServoyName`  | `String` (optional) | The Servoy server name for the clone. Defaults to `newDBNamePostgres` |

```javascript
scopes.svyDeployUtils.createNewCloneOfDatabase('my_database', 'my_database_tenant2', 'tenant2_server');
```

### `initCloneServersBasedOnDatabaseInfo(randomServoyServerName)`

Scans all Postgres databases on the server and automatically registers Servoy server configurations for cloned databases. The mechanism works entirely through the Postgres `COMMENT ON DATABASE` metadata — no extra configuration files needed.

For each database that has a JSON object as its Postgres description, the function checks whether that JSON contains the keys `cloneFromSVYName` and `SVYName`. If both are present and the Servoy server name does not exist yet, it creates the configuration automatically.

**Setting the description on a Postgres database:**

```sql
COMMENT ON DATABASE "my_database_tenant2" IS '{"cloneFromSVYName": "my_database", "SVYName": "tenant2_server"}';
```

| JSON key           | Description                                          |
| ------------------ | ---------------------------------------------------- |
| `cloneFromSVYName` | The Servoy server name to clone the JDBC config from |
| `SVYName`          | The Servoy server name to register for this database |

Once the description is set in Postgres, call this function at startup and Servoy will register `tenant2_server` automatically:

```javascript
// Call once during onSolutionOpen
scopes.svyDeployUtils.initCloneServersBasedOnDatabaseInfo('my_database');
```

Pass any server name that has access to `pg_catalog` — the function queries `pg_database` to find all databases and their descriptions. It only creates configurations for databases that are not already registered in Servoy.

### `removeAllTablesFromDatabase(database)`

Drops all tables in the `public` schema of a Postgres database. Useful for resetting a database to a clean state before running a full data seed.

```javascript
scopes.svyDeployUtils.removeAllTablesFromDatabase('my_database');
```

{% hint style="danger" %}
This function drops all tables permanently. Do not run this in production environments.
{% endhint %}

***

See also: [svyCloud](/reference/servoyextensions/modules/svycloudutils/svycloud.md) for environment detection and tenant session management, and [svyDataSeed](/reference/servoyextensions/modules/svycloudutils/svydataseed.md) for importing seed data after a database reset.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.servoy.com/reference/servoyextensions/modules/svycloudutils/svydeployutils.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
