Google Cloud Spanner Migrations Runner

1.13.0 · active · verified Wed Apr 22

The `google-spanner-migrations-runner` package provides a robust engine for managing schema migrations in Google Cloud Spanner databases, supporting both Google-managed instances and the Spanner emulator. Currently at version 1.13.0, the library receives frequent updates, with minor versions and bug fixes typically released every few months. Unlike ORM-based migration tools, this runner operates directly with `.sql` files, emphasizing a 'migrations-as-code' approach where developers write and test their SQL scripts. It does not generate schema from application code. Key functionalities include applying migrations from a designated directory, validating SQL files, and maintaining a ledger of applied migrations to prevent re-execution. Migrations are applied transactionally and in a specific order, making file naming conventions crucial for successful database evolution. It also features optional annotations for environment-specific migration execution.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically initialize and execute Spanner database migrations using the `SpannerMigration` class, setting up the necessary configuration for connection and specifying the migrations directory.

import { SpannerMigration } from 'google-spanner-migrations-runner';

// A minimal example demonstrating how to programmatically run migrations.
// Ensure you have a 'migrations' directory with .sql files in your project root.
async function main() {
  // Configure Spanner connection and optional environment for annotations.
  const config = {
    projectId: process.env.SPANNER_PROJECT_ID ?? 'your-gcp-project-id',
    instanceId: process.env.SPANNER_INSTANCE_ID ?? 'your-spanner-instance-id',
    databaseId: process.env.SPANNER_DATABASE_ID ?? 'your-spanner-database-id',
    migrationsDir: './migrations', // Path to your SQL migration files
    env: process.env.NODE_ENV ?? 'development' // Optional, for @only-in-env annotations
  };

  // Basic validation for demonstration. In a real app, use proper error handling.
  if (!config.projectId || !config.instanceId || !config.databaseId) {
    console.error('Missing Spanner configuration. Set SPANNER_PROJECT_ID, SPANNER_INSTANCE_ID, SPANNER_DATABASE_ID environment variables.');
    process.exit(1);
  }

  try {
    const runner = new SpannerMigration(config);
    console.log('Starting Spanner migrations...');
    await runner.runMigrations();
    console.log('Spanner migrations completed successfully.');
  } catch (error) {
    console.error('Error running Spanner migrations:', error);
    process.exit(1);
  }
}

main();

// Example content for 'migrations/00001_initial_schema.sql':
// CREATE TABLE users (
//   id INT64 NOT NULL,
//   name STRING(MAX)
// ) PRIMARY KEY (id);

view raw JSON →