Prisma Bypass MySQL
Roda migrations, seeders e SQL avulso direto no MySQL quando o banco não permite prisma migrate deploy / prisma db execute.
🇧🇷 Português (abaixo) | 🇺🇸 English
Por que essa extensão existe
Alguns provedores de MySQL (hospedagem compartilhada, dbaas etc.) não liberam as permissões que o Prisma exige para rodar prisma migrate deploy ou prisma db execute diretamente. Nesses ambientes o fluxo normal do Prisma trava.
Como alternativa, os arquivos de migration/schema/seed continuam sendo gerados normalmente (mantendo a estrutura do Prisma para o dia em que o ambiente mudar), mas precisam ser aplicados manualmente: abrir o .sql, copiar, colar num cliente MySQL e rodar na mão — repetidas vezes, a cada migration.
Essa extensão elimina o copia-e-cola: com um clique no editor, o conteúdo do arquivo (ou só a parte selecionada) é executado direto no banco configurado no .env do projeto, sem sair do VS Code.
Configuração
A extensão lê a conexão do arquivo .env na raiz do workspace aberto, nesta ordem de prioridade:
1. DATABASE_URL (formato padrão do Prisma)
DATABASE_URL="mysql://usuario:senha@host:3306/banco"
2. Variáveis separadas (quando não há uma URL única)
MYSQL_HOST=host
MYSQL_PORT=3306
MYSQL_USER=usuario
MYSQL_PASSWORD=senha
MYSQL_DATABASE=banco
MYSQL_SSL=true
Se nenhuma das duas formas for encontrada, a extensão pede a string de conexão manualmente antes de rodar.
Comandos
Com um arquivo .sql aberto, aparecem dois ícones de play na barra da aba do editor:
| Ícone |
Ação |
Quando aparece |
| ▶ Rodar Arquivo SQL Atual |
Executa o arquivo inteiro |
Sempre, em qualquer .sql |
| ▶ Rodar Seleção SQL |
Executa só o trecho selecionado |
Só quando há texto selecionado |
Ambos também estão disponíveis no clique direito (menu de contexto) e na paleta de comandos (Ctrl+Shift+P → "Prisma Bypass"). Antes de executar, sempre é pedida uma confirmação em modal.
Ao selecionar um trecho de SQL, também aparece um link "▶ Rodar seleção SQL" flutuando na linha logo acima da seleção (CodeLens), sem precisar ir até a barra do editor.
Comandos adicionais via paleta:
- Prisma Bypass: Testar Conexão — roda um
SELECT 1 (leitura, sem risco) para validar as credenciais.
- Prisma Bypass: Rodar Migrations Pendentes — varre
prisma/migrations/*/migration.sql, aplica só as que ainda não constam na tabela de controle _prisma_bypass_migrations (criada automaticamente no banco), na ordem cronológica das pastas. Cada instrução SQL do arquivo roda separadamente: se uma falhar, as demais continuam e no final é exibido um resumo de sucessos/falhas.
- Prisma Bypass: Marcar Migrations Como Aplicadas (sem rodar) — para quando o banco já tem as tabelas/alterações de uma migration (aplicadas manualmente, por outra ferramenta, ou herdadas de antes de usar esta extensão), mas ela ainda não está registrada em
_prisma_bypass_migrations. Abre uma lista das migrations pendentes para você marcar quais já existem no banco — elas passam a contar como aplicadas sem executar o SQL, e o próximo deploy roda só as que realmente faltam.
Detecção automática (migrations e seeds)
A extensão observa o workspace em segundo plano e, quando detecta uma mudança relevante, mostra uma notificação com o botão "Rodar agora" — um clique roda, sem precisar abrir o arquivo ou o comando manualmente:
- Nova migration em
prisma/migrations/*/migration.sql → oferece rodar as migrations pendentes (mesmo fluxo do comando "Rodar Migrations Pendentes").
- Qualquer
.sql alterado direto em prisma/ (ex.: prisma/seed.sql) → oferece rodar aquele arquivo específico no banco.
Isso substitui o clique no ícone de play: você só confirma a notificação. Para evitar disparos em cascata, mudanças próximas no tempo são agrupadas (debounce de ~1s) antes de perguntar.
Por padrão a pasta observada é prisma/, mas nem todo projeto usa esse nome. Se o seu projeto guarda migrations/seeds em outra pasta (ex.: database/), troque em .vscode/settings.json do projeto (não nas configurações globais/de usuário, senão o valor passaria a valer para todo workspace que você abrir):
{
"prismaBypass.rootFolder": "database"
}
A extensão passa a observar database/migrations/*/migration.sql e database/*.sql nesse workspace especificamente; outros projetos continuam usando o padrão prisma/.
Se preferir voltar ao fluxo 100% manual, desative em Configurações → prismaBypass.autoDetect (ou no settings.json do projeto):
"prismaBypass.autoDetect": false
Uso via terminal (sem abrir o VS Code)
Toda a lógica também roda por CLI, útil para automação ou quando você só quer testar rápido:
npm run cli test <caminhoDoProjeto>
npm run cli run <caminhoDoProjeto> <arquivo.sql>
npm run cli deploy <caminhoDoProjeto>
npm run cli status <caminhoDoProjeto>
npm run cli mark-applied <caminhoDoProjeto> <migration1,migration2,...>
run e deploy pedem confirmação digitada (sim) antes de abrir qualquer conexão.
Segurança
- Nenhuma execução acontece sem confirmação explícita do usuário.
- A conexão com o banco é aberta só na hora de rodar o comando e fechada logo em seguida — nunca fica aberta em segundo plano.
- O comando de deploy nunca reaplica uma migration já registrada na tabela
_prisma_bypass_migrations.
Prisma Bypass MySQL (English)
Runs migrations, seeders and ad-hoc SQL directly on MySQL when the database doesn't allow prisma migrate deploy / prisma db execute.
🇺🇸 English (below) | 🇧🇷 Português
Why this extension exists
Some MySQL providers (shared hosting, DBaaS, etc.) don't grant the permissions Prisma requires to run prisma migrate deploy or prisma db execute directly. In these environments, Prisma's normal flow gets stuck.
As a workaround, migration/schema/seed files are still generated normally (keeping Prisma's structure for the day the environment changes), but they need to be applied manually: open the .sql file, copy it, paste it into a MySQL client and run it by hand — repeatedly, for every migration.
This extension removes the copy-paste step: with one click in the editor, the file's content (or just the selected part) is executed directly on the database configured in the project's .env, without leaving VS Code.
Configuration
The extension reads the connection from the .env file at the root of the open workspace, in this priority order:
1. DATABASE_URL (Prisma's default format)
DATABASE_URL="mysql://user:password@host:3306/database"
2. Separate variables (when there's no single URL)
MYSQL_HOST=host
MYSQL_PORT=3306
MYSQL_USER=user
MYSQL_PASSWORD=password
MYSQL_DATABASE=database
MYSQL_SSL=true
If neither is found, the extension asks for the connection string manually before running anything.
Commands
With a .sql file open, two play icons show up in the editor's tab toolbar:
| Icon |
Action |
When it shows up |
| ▶ Run Current SQL File |
Executes the whole file |
Always, on any .sql |
| ▶ Run SQL Selection |
Executes only the selected text |
Only when there's a text selection |
Both are also available via right-click (context menu) and the command palette (Ctrl+Shift+P → "Prisma Bypass"). A confirmation modal is always shown before running anything.
When you select a chunk of SQL, a "▶ Run selection" link (CodeLens) also floats on the line right above the selection, so you don't need to reach for the editor toolbar.
Additional commands via the palette:
- Prisma Bypass: Test Connection — runs a
SELECT 1 (read-only, no risk) to validate the credentials.
- Prisma Bypass: Run Pending Migrations — scans
prisma/migrations/*/migration.sql, applying only the ones not yet recorded in the _prisma_bypass_migrations control table (created automatically in the database), in the folders' chronological order. Each SQL statement in the file runs individually: if one fails, the rest keep going, and a success/failure summary is shown at the end.
- Prisma Bypass: Mark Migrations As Applied (without running) — for when the database already has a migration's tables/changes (applied by hand, by another tool, or from before you started using this extension), but it isn't recorded in
_prisma_bypass_migrations yet. Opens a picker with the pending migrations so you can mark the ones that already exist in the database — they count as applied without running the SQL, and the next deploy only runs what's actually left.
Automatic detection (migrations and seeds)
The extension watches the workspace in the background and, when it detects a relevant change, shows a notification with a "Run now" button — one click runs it, no need to open the file or command manually:
- New migration under
prisma/migrations/*/migration.sql → offers to run the pending migrations (same flow as the "Run Pending Migrations" command).
- Any
.sql file changed directly in prisma/ (e.g. prisma/seed.sql) → offers to run that specific file against the database.
This replaces clicking the play icon: you just confirm the notification. To avoid firing repeatedly, changes that happen close together in time are grouped (debounced ~1s) before asking.
By default the watched folder is prisma/, but not every project uses that name. If your project keeps migrations/seeds in a different folder (e.g. database/), set it in that project's .vscode/settings.json (not in global/user settings, otherwise it would apply to every workspace you open):
{
"prismaBypass.rootFolder": "database"
}
The extension then watches database/migrations/*/migration.sql and database/*.sql for that specific workspace; other projects keep using the prisma/ default.
To go back to a fully manual flow, disable it in Settings → prismaBypass.autoDetect (or in that project's settings.json):
"prismaBypass.autoDetect": false
Terminal usage (without opening VS Code)
All the logic also runs via CLI, useful for automation or a quick manual test:
npm run cli test <projectPath>
npm run cli run <projectPath> <file.sql>
npm run cli deploy <projectPath>
npm run cli status <projectPath>
npm run cli mark-applied <projectPath> <migration1,migration2,...>
run and deploy require a typed confirmation (sim) before opening any connection.
Security
- No execution happens without the user's explicit confirmation.
- The database connection is opened only when running a command and closed right after — it's never kept open in the background.
- The deploy command never reapplies a migration already recorded in the
_prisma_bypass_migrations table.