---
name: azion-seed-a-database-from-a-node-js-script
description: >-
  Load a schema and rows from a SQL file into a SQL Database database with a Node.js script and the @aziontech/sql package of Azion Lib.
---

# Seed a database from a Node.js script

You can load a schema and its first rows into a [SQL Database](/en/documentation/platform/sql-database/) database from a Node.js script. The script uses the `@aziontech/sql` package of [Azion Lib](/en/documentation/devtools/azion-lib/). It reads the statements from a SQL file, so the same file seeds a database in every environment.

---

## Prerequisites

- Node.js and npm. The script is an ES module that uses top-level `await`, and `@aziontech/sql` needs the global `fetch` of Node.js.
- A personal token. To create one, refer to [Manage personal tokens](/en/documentation/guides/platform/account-and-billing/personal-tokens/).
- A database. To create one, refer to [Create and manage databases](/en/documentation/guides/application-development/data/manage-sql-database/). The examples use a database named `storefront-db`.

---

## Install the package

The script imports `@aziontech/sql` from the `node_modules` directory of its project.

In an empty directory, create the project and install the package:

```bash
npm init -y
npm install @aziontech/sql
```

npm prints the new `package.json`, and the install ends with:

```text
added 2 packages, and audited 3 packages in 2s

found 0 vulnerabilities
```

The project has `@aziontech/sql` in its `package.json` dependencies.

---

## Write the seed file

The seed file holds the SQL statements, in the order the database runs them. End each statement with a `;` at the end of its line, because the script splits the file there. A `;` inside a value stays in its statement, as in `'Pen; blue'`.

The database stops at the first statement that fails, and the statements before it stay applied. Because a second run starts again from the first statement, write every statement so that it can run twice. `CREATE TABLE IF NOT EXISTS` skips a table that exists, and `INSERT OR REPLACE` overwrites a row with the same key. For more information, refer to [Send related statements in one call](/en/documentation/platform/sql-database/best-practices/#send-related-statements-in-one-call).

Create a `seed.sql` file:

```sql
CREATE TABLE IF NOT EXISTS products (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL
);
INSERT OR REPLACE INTO products (id, name, price_cents) VALUES (1, 'Notebook', 1290);
INSERT OR REPLACE INTO products (id, name, price_cents) VALUES (2, 'Pen; blue', 350);
INSERT OR REPLACE INTO products (id, name, price_cents) VALUES (3, 'Backpack', 8900);
```

The `seed.sql` file holds one `CREATE TABLE` statement and three `INSERT OR REPLACE` statements.

---

## Write the seed script

The functions of `@aziontech/sql` find a database by a search on its name, and the search also matches part of a name: `storefront` finds `storefront-db`. The script first reads the database with [`getDatabase`](/en/documentation/devtools/azion-lib/sql/#get-a-database) and stops unless its name matches exactly.

The [`useExecute`](/en/documentation/devtools/azion-lib/sql/#execute-statements) function then sends every statement of the file to the database in one call. The [`useQuery`](/en/documentation/devtools/azion-lib/sql/#run-queries) function runs `SELECT COUNT(*)` on the `products` table, so the script confirms the seed. Each function reads your personal token from the `AZION_TOKEN` environment variable.

The script takes the database name as its first argument. Create a `seed.mjs` file:

```javascript
import { readFile } from 'node:fs/promises';
import { getDatabase, useExecute, useQuery } from '@aziontech/sql';

const database = process.argv[2];
const { data: found } = await getDatabase(database);
if (found?.name !== database) {
  console.error(`Seed failed: no database is named ${database}`);
  process.exit(1);
}

const sql = await readFile('seed.sql', 'utf8');
const statements = sql
  .split(/;\s*$/m)
  .map((statement) => statement.trim())
  .filter(Boolean);

const { data, error } = await useExecute(database, statements);
if (error) {
  console.error(`Seed failed: ${error.message}`);
  process.exit(1);
}
console.log(`Ran ${data.results.length} statements on ${database}`);

const { data: check, error: checkError } = await useQuery(database, ['SELECT COUNT(*) FROM products']);
if (checkError) {
  console.error(`Check failed: ${checkError.message}`);
  process.exit(1);
}
console.log(`products has ${check.results[0].rows[0][0]} rows`);
```

When the name check, the seed, or the count fails, the script prints the error and exits with code `1`. The count query names the `products` table: when your seed file creates other tables, name one of them there.

---

## Run the seed

To run the seed:

1. In the terminal where you run the script, store your personal token in the `AZION_TOKEN` variable. Replace `[TOKEN VALUE]` with your token:

   ```bash
   export AZION_TOKEN=[TOKEN VALUE]
   ```

   Every script you start from this terminal reads the token, until the terminal closes.

2. Run the script with the full name of your database:

   ```bash
   node seed.mjs storefront-db
   ```

   ```text
   Ran 4 statements on storefront-db
   products has 3 rows
   ```

3. (Optional) Run the script again. The statements skip the existing table and overwrite the rows, so the count stays the same:

   ```bash
   node seed.mjs storefront-db
   ```

   ```text
   Ran 4 statements on storefront-db
   products has 3 rows
   ```

The database holds the `products` table and its three rows.

When no database has the exact name you passed, such as `storefront`, the script prints `Seed failed: no database is named storefront` and writes nothing. When a statement fails, it prints the database error, such as `Seed failed: no such table: nope`.

---

## Next steps

- [Azion Lib SQL](/en/documentation/devtools/azion-lib/sql.md): Every function of @aziontech/sql, its parameters, and its response envelope.
- [SQL Database](/en/documentation/platform/sql-database.md): How a statement runs on a database, its results, and the bounds of a database.
