DEV Community

loading...

How to use a MySQL database on GitHub Actions

Freek Van der Herten
PHP developer and package creator at Spatie
Originally published at freek.dev ・2 min read

Recently we started using GitHub Actions to test all our packages. You can read more about our general setup in this blog post.

For most of the packages, this works great. However, some of our packages, such as Laravel Tags, use JSON functions that are not available in SQLite. Luckily it's straightforward to use a database like MySQL in GitHub Actions.

In your test workflow, you need to add MySQL to the services.

services:
    mysql:
        image: mysql:5.7
        env:
            MYSQL_ALLOW_EMPTY_PASSWORD: yes
            MYSQL_DATABASE: laravel_tags
        ports:
            - 3306
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

In the step that executes the test, you should add an env variable DB_PORT. Laravel uses that environment variable to set up the connection to the database.

- name: Execute tests
  run: vendor/bin/phpunit
  env:
      DB_PORT: ${{ job.services.mysql.ports[3306] }}

In phpunit.xml.dist you should add this section.

<php>
    <env name="DB_CONNECTION" value="mysql"/>
    <env name="DB_USERNAME" value="root"/>
    <env name="DB_DATABASE" value="laravel_tags"/>
    <env name="DB_HOST" value="127.0.0.1" />
    <env name="DB_PORT" value="3306" />
</php>

That DB_PORT there is used for local tests. On GitHub Actions, it will be overwritten by the port set in the workflow.

And that is all there is to it. Take a look at the entire GitHub Actions workflow and phpunit config file, to get a little bit more context where you need to use the code snippets above.

Discussion (0)