# Neo4J migrations with liquibase

## When to use this migration style

- Neo4j DDL statements.
- Minor data changes using specific record ids.
- Short running queries (less than 5 minutes)


### Oficial documentation

[Liquibase documentation](https://neo4j.com/labs/liquibase/docs/download/#__tabbed_1_2)

### How can I create a migration

- Put your migration files under `/{neo4j-db-name}/build/changelog/dml` directory
- Both .xml and .cypher changesets are supported
- No special rollback sections/tags. To rollback a migration you will have 
to create a new migration with rollback queries manually.
- The changeset id must be unique across all changesets. Follow best practices below to ensure this.

### Best Practices

- Only one file per PR.
- Changeset id should match the file (minuse '.xml' filetype)
- If multiple changesets in a file, append the sequence number of the changeset
- Changesets that create 100s of nodes and edges may exceed the 5-minute timeout. Break up large queries into multiple, smaller changesets. 
- Use [EXPLAIN](https://neo4j.com/docs/cypher-manual/current/execution-plans/) to verify the query plan does not include a [NodeByLabelScan](https://neo4j.com/docs/cypher-manual/current/execution-plans/operators/#query-plan-node-by-label-scan).

### Migration example
Filename: migration_example.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:neo4j="http://www.liquibase.org/xml/ns/dbchangelog-ext"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-latest.xsd">
    <changeSet id="migration_example:1" author="jdiaz85">
        <neo4j:cypher>CREATE (:Movie {title: 'My Life99'})</neo4j:cypher>
    </changeSet>
</databaseChangeLog>
``` 

Filename: migration_example.cypher
```
--liquibase formatted cypher

--changeset jdiaz85:my-movie-init
CREATE (:Movie {title: 'My Life'})
``` 

### Running a Migration Locally
```
mvn -f build/pom.xml initialize package -DchangeLogFile=db-migration-you-want-to-run.xml
```

### Browsing Changsets
See all changesets in the changelog
```
MATCH (lcl:__LiquibaseChangelog)-[r]-(lcs)
 return lcl,r,lcs;
```

See all changesets with id like PLATFORM-1624_cleanup_sample_data*
```
MATCH (lcl:__LiquibaseChangelog)-[r]-(lcs)
WHERE lcs.id STARTS WITH 'PLATFORM-1624_cleanup_sample_data'
 return lcl,r,lcs;
```

See changeset exactly matching id=PLATFORM-1624_cleanup_sample_data:3
```
MATCH (lcl:__LiquibaseChangelog)-[r]-(lcs)
WHERE lcs.id=PLATFORM-1624_cleanup_sample_data:3
 return lcl,r,lcs;
```
