db3.aiVisit main site

14 October 2026

Seeding Database Environments Safely: Reference Data, Local Samples, and Tests

TL;DR

For safe database seeding, migrate the schema first, put required reference rows in their own repeatable seed, and keep synthetic local samples and test fixtures out of production. Run each dataset against an explicitly approved database, then run it again and check the actual rows. Below, we use a small MariaDB reference-data example and verify the result through a db3.ai ActiveRecord model.

A fresh environment needs more than empty tables. An application may expect a handful of role codes before it can show useful behavior; a developer may want believable sample records; a test needs its own tightly scoped setup. Treating all three as one seed command creates a dangerous choice: either production receives demo users, or local and test environments are difficult to reproduce.

Seeding a database means inserting an initial set of records into an existing schema. It is distinct from creating the schema, generating per-test fixtures, or importing customer data. Supabase's database seeding guide runs seeds after migrations and recommends keeping schema statements out of seed files. We will follow that separation, while making the environment boundary more explicit than a single seed.sql file can express.

Prerequisites: You need control of a disposable MariaDB/MySQL database, a database login limited to that environment, access to your application's schema/migration files, and permission to inspect the resulting rows. For the db3.ai check, use an application with the matching preview @db3.ai/app packages already installed, its App booted against the approved database, and a model registered against the same table. The installation guide explains current package availability and why an inherited DATABASE_URL must be checked. Our new SQL and TypeScript snippets are instructional examples, not a claim that we ran them against your app.

Table of contents

1. Decide what each database is allowed to receive

Before writing an insert, put your intended records into three buckets. Reference data is a small, reviewed set the application needs, such as role codes or status names. Local/demo data illustrates a product journey with synthetic organizations, accounts and related records. Test fixtures set up only what a specific test needs and are discarded with that test's database. A production import, by contrast, has an external source, mapping rules and reconciliation requirements; do not rename it a seed to bypass review.

Destination Appropriate starting data How to trigger it
Local development Reviewed reference rows, then optional synthetic examples Deliberate local initialization
Automated tests Reference rows when required, plus test-owned fixtures Isolated test setup and teardown
Preview/demo Reference rows and a clearly approved synthetic demo dataset Environment-specific deployment step
Production Only reviewed, necessary reference rows Restricted initialization or reviewed release step

For example, a viewer role code might exist everywhere. A fictional account and several notes should be optional in local development or a preview; they should never be inserted into a customer database just because the same deployment pipeline runs there. Use reserved example addresses instead of personal email, and never put working provider keys or real customer records in seeds.

Check: Every proposed row has a named destination and owner. If you cannot decide whether a record is application-required or just convenient for a screenshot, keep it out of the production baseline.

2. Apply the schema before any seed data

Write and review the table definition as a migration, then apply it to the selected database before running seeds. For the db3.ai starter, the documented sequence is npm run db:migrate followed by npm run db:check; its migration guide keeps committed schema changes separate from disposable Database.install() examples. Do not run table installation in application startup to make a seed pass.

Here is the illustrative schema for our reference-data lab. Execute it only in a newly created, disposable MariaDB database for this walkthrough, or translate it into a reviewed application migration. It is not part of the seed file. If your application already owns a roles table, use its actual schema instead of creating another one.

CREATE TABLE seed_roles (
  id CHAR(26) NOT NULL PRIMARY KEY,
  code VARCHAR(32) NOT NULL UNIQUE,
  label VARCHAR(80) NOT NULL
);

The database-enforced unique code is important: the seed can identify a logical role even when called more than once. The fixed id values in the next step are illustration-only identities for this brand-new table. Never reuse those IDs for a different meaning or overwrite existing production roles to make this example fit. In an actual db3.ai app, register the corresponding model and generate, review and apply the migration according to your app's registry and CLI rather than treating the SQL above as a framework-generated migration.

Think of the environment sequence as schema, approved reference rows, optional dependent sample rows, then verification. Foreign-key children belong after their parents, with real persisted parent IDs rather than guessed ones.

Seeding workflow from migrated schema through ordered data to isolated verification

Check: The intended database has the seed_roles table and a unique constraint on code; in a db3.ai starter, db:check should report no pending schema mismatch. If a seed reports a missing table, stop and check the connection and migration status instead of pointing it at another database.

3. Seed stable reference rows without duplicating them

Save the following as an application-owned SQL seed for MariaDB, separate from migration files and from demo fixtures. Run it using your team's approved database client against the disposable database named and inspected in step 2. Do not run it in an unreviewed shell that might inherit a production connection. MariaDB's documented INSERT ... ON DUPLICATE KEY UPDATE updates a row when a primary or unique key conflicts; the example uses it to keep each known role's label current.

START TRANSACTION;

INSERT INTO seed_roles (id, code, label) VALUES
  ('01ARZ3NDEKTSV4RRFFQ69G5FAV', 'viewer', 'Viewer'),
  ('01ARZ3NDEKTSV4RRFFQ69G5FAW', 'editor', 'Editor')
ON DUPLICATE KEY UPDATE label = VALUES(label);

COMMIT;

Repeat the script against that same database, then inspect it:

SELECT code, label, id
FROM seed_roles
WHERE code IN ('viewer', 'editor')
ORDER BY code;

You should see exactly one editor and one viewer, with the expected labels and unchanged IDs after the second pass. This is an expected outcome, not an observed execution result. An unexpected existing row with one of these IDs or codes is a conflict to investigate, not permission to overwrite it. MariaDB's duplicate-key behavior can match a primary key or another unique index, so design the seed's ownership policy before using it on established data. If a statement fails, stop that session and roll back rather than proceeding to COMMIT; MariaDB's transaction documentation covers transaction boundaries. Keep schema-changing DDL out of this transaction.

A rerunnable seed should also have a policy for removals. This script does not delete old role codes; deleting a role could invalidate existing memberships. Use a separately reviewed data change to retire a reference value, after checking which records still depend on it.

Check: The second run leaves the two intended records unchanged. If counts grow, inspect the unique key and the actual target database. A transaction does not replace uniqueness or prevent incompatible seed versions from competing in two concurrent deployments; serialize initialization for a given environment.

4. Verify the reference rows from a db3.ai application

A successful SQL command is not yet proof that your TypeScript runtime can read the same database. In a db3.ai application that already boots one App and has registered its models, map the migrated table to an ActiveRecord model. The package's ActiveRecord guide documents ActiveRecord.define(), field declarations and queries; where(...).firstOrFail() is documented in its API reference. This is an example model for the lab, not a claim that the starter ships ReferenceRole or a seeding CLI.

import { ActiveRecord } from '@db3.ai/app/db';

export class ReferenceRole extends ActiveRecord.define({
  table: 'seed_roles',
  fields(field) {
    return {
      id: field.ulid(),
      code: field.string({ required: true, maxLength: 32 }),
      label: field.string({ required: true, maxLength: 80 }),
    };
  },
}) {}

export async function verifyReferenceRoles(): Promise<void> {
  const viewer = await ReferenceRole.where('code', 'viewer').firstOrFail();
  const editor = await ReferenceRole.where('code', 'editor').firstOrFail();
  if (viewer.label !== 'Viewer' || editor.label !== 'Editor') {
    throw new Error('Reference roles do not match the reviewed seed.');
  }
}

Place this in your own app, register ReferenceRole in its model registry, and call verifyReferenceRoles() from a deliberate verification command or integration test after migrations and the approved reference seed. Your host must already have started its App with the intended database connection; this function does not boot the runtime or select a connection. Match the model definition, column lengths and migration in your installed version, and type-check and run an isolated SQL test before adopting the snippet. A missing row should fail loudly rather than quietly producing a default role. For the broader data model workflow, follow the db3.ai model and persistence walkthrough.

Check: Both lookups succeed and labels match. If SQL inspection passed but this function fails, compare the App's actual connection settings, table mapping and migration state; do not weaken the assertion.

5. Add optional sample data only where it belongs

Once the baseline works, build a separate local/demo dataset. Create a fictional organization first, then synthetic users, memberships and notes. Retrieve each saved parent's ID before creating its children, and keep foreign keys enforced. The organization slug and example-domain email can serve as stable lookup keys; an arbitrary generated ID from an earlier machine cannot. For a developer who wants a runnable db3.ai seeder built around notes, our separate TypeScript database seeder walkthrough covers that implementation without mixing its disposable notes lab into this reference-data workflow.

Protected production reference data separated from disposable development sample data

Tests usually need less data than demos. A test for an unauthorized note should construct just the required account, workspace and note in its own disposable database, then clean up in teardown. The db3.ai testing guide documents isolated generated test databases, separate configuration and cleanup; do not reuse a developer's persistent local database for a suite that reshapes tables. A factory can produce varied synthetic values, but pin meaningful identities and clocks when assertions depend on them.

Check: Switching off demo initialization leaves required role codes intact; starting a clean test database does not pull in unrelated local accounts. If a foreign key fails, verify seed ordering and persisted parent IDs before disabling constraints.

6. Make environment initialization a repeatable release check

Test the whole sequence on a fresh disposable environment: apply committed migrations, run reference seeding twice, execute the db3.ai lookup, and then add the environment's optional data. Record the database name, migration revision and seed version in deployment logs without logging passwords or personal data. Test an existing-data upgrade separately; an empty-database pass cannot prove a later migration preserves earlier records. The db3.ai migration workflow specifically distinguishes fresh setup from additive changes to stored data.

For a production release, narrow the actor's permissions and have one reviewed initializer run once per intended database. Microsoft warns about running custom initialization during ordinary multi-instance app startup because concurrent instances can interfere. That warning applies as a design consideration here, not as a claim that db3.ai provides EF Core's migration lock or its seeding hooks. Build your own explicit deployment boundary; do not assume a successful transaction makes two independent initializers mutually exclusive.

If an initialization fails halfway, stop the deployment and inspect which phase committed: schema migration, reference rows or optional demo layer. MariaDB schema DDL is not generally reversible within the same transaction, as the db3.ai migration guide notes, so a failed migration calls for a reviewed forward repair rather than a blind rerun of everything. Keep seed output concise enough to tell an operator which environment and phase failed.

Check: A clean install and a rerun against the same database both pass, while a test deliberately pointed at an unapproved database is refused by your deployment policy. Review the target and grants outside the seed script as well as inside it.

We would begin with the smallest shared reference dataset your app genuinely needs. Run the local sequence in a disposable database, connect your verified db3.ai model, and only then add separate synthetic data for developers. That produces a usable initialized environment without making the demo dataset part of production policy.

Sources