Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
bplunkett-stripe committed Jun 2, 2023
0 parents commit 53ff525
Show file tree
Hide file tree
Showing 68 changed files with 15,369 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[{*.go,Makefile,.gitmodules,go.mod,go.sum}]
indent_style = tab

[*.md]
indent_style = tab
trim_trailing_whitespace = false

[*.{yml,yaml,json}]
indent_style = space
indent_size = 2

[*.{js,jsx,ts,tsx,css,less,sass,scss,vue,py}]
indent_style = space
indent_size = 4
23 changes: 23 additions & 0 deletions .github/workflows/code-gen.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: code_gen
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
code_gen:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker image
run: docker build -t pg-schema-diff-code-gen-runner -f ./build/Dockerfile.codegen .
- name: Run codegen
run: docker run -v $(pwd):/pg-schema-diff -w /pg-schema-diff pg-schema-diff-code-gen-runner
- name: Check for changes
run: |
chmod +x ./build/ci-scripts/assert-no-diff.sh
./build/ci-scripts/assert-no-diff.sh
shell: bash

21 changes: 21 additions & 0 deletions .github/workflows/lint.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: lint
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v4
with:
go-version: '1.18'
cache: false
- uses: actions/checkout@v3
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.52.2
20 changes: 20 additions & 0 deletions .github/workflows/run-tests.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: run_tests

on:
push:
branches:
- main
pull_request:
jobs:
run_tests:
runs-on: ubuntu-latest
strategy:
matrix:
pg_version: [14, 15]
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Build Docker image
run: docker build -t pg-schema-diff-test-runner -f ./build/Dockerfile.test --build-arg POSTGRES_PACKAGE=postgresql${{ matrix.pg_version }} .
- name: Run tests
run: docker run pg-schema-diff-test-runner
26 changes: 26 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Mac OS X files
.DS_Store

# Binaries for programs and plugins
bin/
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, build with `go test -c`
*.test
!/build/Dockerfile.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

# Dependency directories
vendor/

# Intellij
.idea/
9 changes: 9 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
linters:
disable-all: true
enable:
- goimports
- ineffassign
- staticcheck
- typecheck
- unused

76 changes: 76 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at conduct@stripe.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
24 changes: 24 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Contributing

This project is in its early stages. We appreciate all the feature/bug requests we receive, but we have limited cycles
to review direct code contributions at this time. We will try and respond to any bug reports, feature requests, and
questions within one week.

If you want to make changes yourself, follow these steps:

1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository and [clone](https://help.github.com/articles/cloning-a-repository/) it locally.
2. Make your changes
3. Test your changes
```bash
docker build -t pg-schema-diff-test-runner -f ./build/Dockerfile.test --build-arg POSTGRES_PACKAGE=postgresql{14, 15} .
```
3. Submit a [pull request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/)

## Contributor License Agreement ([CLA](https://en.wikipedia.org/wiki/Contributor_License_Agreement))

Once you have submitted a pull request, sign the CLA by clicking on the badge in the comment from [@CLAassistant](https://github.com/CLAassistant).

<img width="910" alt="image" src="https://user-images.githubusercontent.com/62121649/198740836-70aeb322-5755-49fc-af55-93c8e8a39058.png">

<br />
Thanks for contributing to Stripe!
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License

Copyright (c) 2023- Stripe, Inc. (https://stripe.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
16 changes: 16 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.PHONY: code_gen format lint test vendor sqlc

code_gen: sqlc

format:
goimports -w .

lint:
golangci-lint run

sqlc:
cd internal/queries && sqlc generate

vendor:
go mod vendor

104 changes: 104 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# pg-schema-diff

Diffs Postgres database schemas and generates the the SQL required to get your database schema from point A to B. This
enables you to take your database and migrate it to any desired schema defined with plain DDL.

The tooling attempts to use native postgres migration operations and avoid locking wherever possible. Not all migrations will
be lock-free and some might require downtime, but the hazards system will warn you ahead of time when that's the case.
Stateful online migration techniques, like shadow tables, aren't yet supported.

```
pg-schema-diff plan --dsn "postgres://postgres:postgres@localhost:5432/postgres" --schema-dir schema
################################ Generated plan ################################
1. ALTER TABLE "foobar" ADD COLUMN "fizz" character varying(255) COLLATE "pg_catalog"."default";
-- Timeout: 3s
2. CREATE INDEX CONCURRENTLY fizz_idx ON public.foobar USING btree (fizz);
-- Timeout: 20m0s
-- Hazard INDEX_BUILD: This might affect database performance. Concurrent index builds require a non-trivial amount of CPU, potentially affecting database performance. They also can take a while but do not lock out writes.
```

# Key features
*Broad support for diffing & applying arbitrary postgres schemas defined in declarative DDL:*
- Tables
- Columns
- Check Constraints
- Indexes
- Partitions
- Functions/Triggers (functions created by extensions are ignored)

*A comprehensive set of features to ensure the safety of planned migrations:*
- Dangerous operations are flagged as hazards and must be approved before a migration can be applied.
- Data deletion hazards identify operations which will in some way delete or alter data.
- Downtime/locking hazards identify operations which will impede or stop other queries.
- Performance hazards identify operations which are resource intensive and might slow other queries.
- Migration plans are validated first against a temporary database exactly as they would be performed against the real database.
- The library is tested against an extensive suite of unit and acceptance tests.

*The use of postgres native operations for zero-downtime migrations wherever possible:*
- Concurrent index builds
- Online index replacement

# Install
## Library
```bash
go get -u github.com/stripe/pg-schema-diff
````
## CLI
```bash
go install github.com/stripe/pg-schema-diff/cmd/pg-schema-diff
```

# Using CLI
## 1. Apply schema to fresh database
Create a directory to hold your schema files. Then, generate sql files and place them into a schema dir.
```bash
mkdir schema
echo "CREATE TABLE foobar (id int);" > schema/foobar.sql
echo "CREATE TABLE bar (id varchar(255), message TEXT NOT NULL);" > schema/bar.sql
```

Apply the schema to a fresh database. [The connection string spec can be found here](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING).
Setting the `PGPASSWORD` env var will override any password set in the connection string and is recommended.
```bash
pg-schema-diff apply --dsn "postgres://postgres:postgres@localhost:5432/postgres" --schema-dir schema
```

## 2. Updating schema
Update the SQL file(s)
```bash
echo "CREATE INDEX message_idx ON bar(message)" >> schema/bar.sql
```

Apply the schema. Any hazards in the generated plan must be approved
```bash
pg-schema-diff apply --dsn "postgres://postgres:postgres@localhost:5432/postgres" --schema-dir schema --allow-hazards INDEX_BUILD
```

# Supported Postgres versions
- 14 (tested with 14.7)
- 15 (tested with 15.2)

Postgres v13 and below are not supported. Use at your own risk.

# Unsupported migrations
Note, the library only currently supports diffing the *public* schema. Support for diffing other schemas is on the roadmap

*Unsupported*:
- (On roadmap) Foreign key constraints
- (On roadmap) Diffing schemas other than "public"
- (On roadmap) Serials and sequences
- (On roadmap) Unique constraints (unique indexes are supported but not unique constraints)
- (On roadmap) Adding and remove partitions from an existing partitioned table
- (On roadmap) Check constraints localized to specific partitions
- Partitioned partitions (partitioned tables are supported but not partitioned partitions)
- Materialized views
- Renaming. The diffing library relies on names to identify the old and new versions of a table, index, etc. If you rename
an object, it will be treated as a drop and an add

# Contributing
This project is in its early stages. We appreciate all the feature/bug requests we receive, but we have limited cycles
to review direct code contributions at this time. See [Contributing](CONTRIBUTING.md) to learn more.


10 changes: 10 additions & 0 deletions build/Dockerfile.codegen
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM golang:1.18.10-alpine3.17

RUN apk update && \
apk add --no-cache \
build-base \
git \
make

RUN go install github.com/kyleconroy/sqlc/cmd/sqlc@v1.13.0
ENTRYPOINT make code_gen
Loading

0 comments on commit 53ff525

Please sign in to comment.