github actions - 在 postgres 服务中运行 sql 脚本

asu*_*sus 8 postgresql github-actions

我想在 github actions 的 postgres 服务中运行一个脚本,创建一个表并添加一个扩展。我怎样才能做到这一点?我需要制作 shell 脚本还是可以直接在 yaml 文件中执行?

SQL脚本

drop database mydb;
create database mydb;
\c mydb;
CREATE EXTENSION "pgcrypto";
Run Code Online (Sandbox Code Playgroud)

工作流程

name: API Integration Tests

on: 
    pull_request:
    push:
        branches:
            -master

env:
    DB_HOST: localhost
    DB_USERNAME: postgres
    DB_PASSWORD: rt

jobs:
    build:
        runs-on: ubuntu-latest

        strategy:
          matrix:
            node-version: [10.x, 12.x, 13.x]


    services:
        postgres:
          image: postgres:latest
          env:
            POSTGRES_DB: mydb        
            POSTGRES_PASSWORD: helloworl
            POSTGRES_USER: postgres
          ports:
            - 5433:5432
          # Set health checks to wait until postgres has started
          options: >-
            --health-cmd pg_isready
            --health-interval 10s
            --health-timeout 5s
            --health-retries 5
    steps:
        - uses: actions/checkout@v1
        - name: Use Node.js ${{ matrix.node-version }}
            uses: actions/setup-node@v1
            with:
            node-version: ${{ matrix.node-version }}
        - name: npm install
            run: npm ci
        - name: npm test
            run: npm run test

Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 4

您可以添加使用 PSQL 命令的步骤。

以下是创建数据库的示例步骤:

- name: Create database
  run: |
     PGPASSWORD=helloworl psql -U postgres -tc "SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')"
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我注意到您想要的下一个命令是:CREATE EXTENSION "pgcrypto";,我认为这是因为您想要生成 UUID(常见用例)。请注意,您不需要这个,get_random_uuid()因为这是从 v13 开始的 Postgres 本身支持的。

但是,如果您真的非常非常想添加 pgcrypto,您可以使用此步骤:

- name: Enable pgcrypto extension
  run: |
     PGPASSWORD=helloworl psql -U postgres -tc "CREATE EXTENSION 'pgcrypto';"
Run Code Online (Sandbox Code Playgroud)