drizzle-kit 0.9.2 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/{dist/drizzle.js → drizzle.js} +0 -0
  2. package/{dist/drizzle.js.map → drizzle.js.map} +0 -0
  3. package/package.json +1 -1
  4. package/.eslintrc +0 -21
  5. package/config.yml +0 -4
  6. package/data/_prev/multi.ts +0 -43
  7. package/data/_prev/tables/authOtpTable.ts +0 -22
  8. package/data/_prev/tables/cityTable.ts +0 -17
  9. package/data/_prev/tables/usersTable.ts +0 -18
  10. package/data/_prev/types/types.ts +0 -11
  11. package/data/v1/tables/authOtpTable.ts +0 -18
  12. package/data/v1/tables/deletedTable.ts +0 -9
  13. package/data/v1/tables/usersTable.ts +0 -15
  14. package/data/v1/types/types.ts +0 -6
  15. package/data/v2/tables/authOtpTable.ts +0 -22
  16. package/data/v2/tables/cityTable.ts +0 -10
  17. package/data/v2/tables/usersTable.ts +0 -19
  18. package/data/v2/types/types.ts +0 -11
  19. package/data/v3/tables/authOtpTable.ts +0 -21
  20. package/data/v3/tables/cityTable.ts +0 -17
  21. package/data/v3/tables/usersTable.ts +0 -18
  22. package/data/v3/types/types.ts +0 -11
  23. package/dist/package.json +0 -85
  24. package/factory.ts +0 -224
  25. package/fstest.ts +0 -50
  26. package/index.ts +0 -16
  27. package/readme.md +0 -9
  28. package/serializer.ts +0 -139
  29. package/src/cli/commands/migration/index.tsx +0 -10
  30. package/src/cli/commands/migration/migrate/index.tsx +0 -164
  31. package/src/cli/components-api/ComponentsList.tsx +0 -20
  32. package/src/cli/components-api/CreateApp.tsx +0 -19
  33. package/src/cli/components-api/components/PromptColumnsConflicts.tsx +0 -171
  34. package/src/cli/components-api/components/PromptTablesConflicts.tsx +0 -180
  35. package/src/cli/components-api/components/Task.tsx +0 -85
  36. package/src/cli/components-api/index.tsx +0 -76
  37. package/src/cli/enq.ts +0 -41
  38. package/src/cli/index.tsx +0 -8
  39. package/src/cli/machines/resolveColumnsMachine.ts +0 -179
  40. package/src/cli/machines/resolveTablesMachine.ts +0 -169
  41. package/src/cli/utils/formatDataForTable.ts +0 -36
  42. package/src/cli/utils/valuesForPrompts.ts +0 -35
  43. package/src/diff.ts +0 -272
  44. package/src/differ.js +0 -135
  45. package/src/jsonStatements.js +0 -176
  46. package/src/migrationPreparator.ts +0 -47
  47. package/src/serilizer/factory.ts +0 -340
  48. package/src/serilizer/index.ts +0 -25
  49. package/src/simulator.ts +0 -85
  50. package/src/sqlgenerator.js +0 -373
  51. package/test-build.js +0 -26
  52. package/test.ts +0 -57
  53. package/testFactory.js +0 -3
  54. package/testFactory.ts +0 -26
  55. package/tsconfig.json +0 -28
  56. package/webpack.config.js +0 -53
package/fstest.ts DELETED
@@ -1,50 +0,0 @@
1
- import fs from 'fs'
2
- import serialize from './src/serilizer'
3
-
4
- // TODO: export as a function w
5
-
6
- const dry = {
7
- version: "1",
8
- tables: {},
9
- enums: {}
10
- }
11
-
12
- const prepareMigration = (path: string = 'drizzle'): {} => {
13
- const root = path
14
- const files = fs.readdirSync('./')
15
- const drizzleFolder = files.find((it) => {
16
- return it === root
17
- })
18
-
19
- if (!drizzleFolder) {
20
- fs.mkdirSync(root)
21
- }
22
-
23
- const migrationFolders = fs.readdirSync(`./${root}`)
24
-
25
- let prevSnapshot;
26
-
27
- if (migrationFolders.length === 0) {
28
- prevSnapshot = dry
29
- } else {
30
- migrationFolders.sort()
31
- const lastSnapshotFolder = migrationFolders[migrationFolders.length - 1]
32
- prevSnapshot = fs.readFileSync(`./${root}/${lastSnapshotFolder}/snapshot.json`).toJSON()
33
- }
34
-
35
- const timestamp = Date.now()
36
- const migrationFolder = `./${root}/${timestamp}`
37
- fs.mkdirSync(migrationFolder)
38
-
39
- const version = 'v3'
40
- const dir = `./data/${version}`
41
- const tbls = `${dir}/tables/`
42
- const tps = `${dir}/types/`
43
-
44
- const result = serialize(tbls, tps)
45
- fs.writeFileSync(`${migrationFolder}/snapshot.json`, JSON.stringify(result, null, 2))
46
-
47
- return { prev: prevSnapshot, cur: result }
48
- }
49
-
50
- export default prepareMigration;
package/index.ts DELETED
@@ -1,16 +0,0 @@
1
- import serialize from './src/serilizer'
2
- import yaml from 'js-yaml'
3
- import fs from 'fs'
4
-
5
- const version = 'v2'
6
- const dir = `./data/${version}`
7
- const tbls = `${dir}/tables/`
8
- const tps = `${dir}/types/`
9
-
10
- // const config: Config = yaml.load(fs.readFileSync('config.yml', {encoding: 'utf-8'})) as Config;
11
- // console.log(config)
12
-
13
- const result = serialize(tbls, tps)
14
- const outName = `${version}_${new Date().getTime()}.json`
15
- fs.writeFileSync(`./out/${outName}`, JSON.stringify(result, null, 2))
16
- console.log(`-----> .../${outName}`)
package/readme.md DELETED
@@ -1,9 +0,0 @@
1
- todo: configurable migrations folder
2
- todo: configurable tables and enums folder
3
- todo: ability to just have single folder with either tables and enums in one file or spreaded in multiple files
4
-
5
- stage0 -> fstest.js
6
- it does check if migration folder exists, if not - creates one. Checks if initial migration exists, if not - creates one and initiate init migration generation with dryrun snapshot1. If init migration exists - initiate migration generation with last chronologically available snapshot folder.
7
-
8
- stage1 -> ./index.ts
9
- It is now harcoded, what it does - it takes directory for tables and enums and generates json snapshot of the whole project schema.
package/serializer.ts DELETED
@@ -1,139 +0,0 @@
1
- /* eslint-disable no-restricted-syntax */
2
- /* eslint-disable new-cap */
3
- /* eslint-disable global-require */
4
- /* eslint-disable import/no-dynamic-require */
5
- import { AbstractTable, Column, DB } from 'drizzle-orm';
6
- import ColumnType from 'drizzle-orm/columns/types/columnType';
7
- import PgEnum from 'drizzle-orm/columns/types/pgEnum';
8
- import TableIndex from 'drizzle-orm/indexes/tableIndex';
9
- import Enum from 'drizzle-orm/types/type';
10
- import { Pool } from 'pg';
11
-
12
- interface ColumnAsObject {
13
- [name: string]: {
14
- name?: string;
15
- type?: string;
16
- primaryKey?: boolean;
17
- autoincrement?: boolean;
18
- unique?: boolean;
19
- default?: any;
20
- notNull?: boolean;
21
- references?: {
22
- table: string;
23
- column: string;
24
- };
25
- };
26
- }
27
-
28
- interface IndexColumnAsObject {
29
- [name: string]: {
30
- name?: string;
31
- };
32
- }
33
-
34
- interface IndexAsObject {
35
- [name: string]: {
36
- name?: string;
37
- columns?: ColumnAsObject;
38
- };
39
- }
40
-
41
- interface TableAsObject {
42
- [name: string]: {
43
- name: string;
44
- columns: ColumnAsObject;
45
- indexes: {
46
- [name: string]: {
47
- name?: string;
48
- type?: string;
49
- };
50
- };
51
- };
52
- }
53
-
54
- interface EnumAsObject {
55
- [name: string]: {
56
- name: string;
57
- values: string[];
58
- };
59
- }
60
-
61
- export default class MigrationSerializer {
62
- db = new DB(new Pool());
63
-
64
- public generate = (tables: AbstractTable<any>[], enums: Enum<any>[]) => {
65
- const result: TableAsObject = {};
66
-
67
- for (const table of tables) {
68
- const tableEntries = Object.entries(table);
69
- const columnToReturn: ColumnAsObject = {};
70
- const indexToReturn: IndexAsObject = {};
71
-
72
- for (const properties of tableEntries) {
73
- const key = properties[0];
74
- const value = properties[1];
75
- if (value instanceof TableIndex) {
76
- const columns = value.getColumns();
77
- const name = value.indexName();
78
-
79
- const indexColumnToReturn: IndexColumnAsObject = {};
80
-
81
- for (const column of columns) {
82
- const columnName = column.getColumnName();
83
- indexColumnToReturn[columnName] = {
84
- name: columnName,
85
- };
86
- }
87
-
88
- indexToReturn[name] = {
89
- name,
90
- columns: indexColumnToReturn,
91
- };
92
- }
93
-
94
- if (value instanceof Column) {
95
- columnToReturn[key] = {
96
- name: value.getColumnName(),
97
- type: (value.getColumnType() as ColumnType).getDbName(),
98
- primaryKey: !!value.primaryKeyName,
99
- autoincrement: value.isAutoIncrement(),
100
- unique: !!value.uniqueKeyName,
101
- default: value.getDefaultValue() === null ? undefined : value.getDefaultValue(),
102
- notNull: !value.isNullableFlag,
103
- };
104
-
105
- const referenced = value.getReferenced();
106
- if (referenced) {
107
- columnToReturn[key].references = {
108
- table: referenced.getParentName(),
109
- column: referenced.getColumnName(),
110
- };
111
- }
112
- }
113
- }
114
-
115
- result[table.tableName()] = {
116
- name: table.tableName(),
117
- columns: columnToReturn,
118
- indexes: indexToReturn,
119
- };
120
- }
121
-
122
- // const enumsToReturn = enums.map((it) => {
123
- // return { name: it.name, values: it.values }
124
- // });
125
-
126
- const enumsToReturn = enums.reduce<{[key:string]: Enum<any>}>((map, obj) => {
127
- const key = obj.name;
128
- const newValues = obj.values.reduce((mapped, value) => {
129
- mapped[value] = value;
130
- return mapped;
131
- }, {});
132
-
133
- map[key] = { name: obj.name, values: newValues };
134
- return map;
135
- }, {});
136
-
137
- return { version: '1', tables: result, enums: enumsToReturn };
138
- };
139
- }
@@ -1,10 +0,0 @@
1
- import { program } from 'commander';
2
-
3
- import migrate from './migrate';
4
-
5
- const cmd = program
6
- .command('migrate')
7
- .alias('mg')
8
- .description('Migration')
9
- .action(migrate);
10
- cmd.command('start').description('Start migration').action(migrate);
@@ -1,164 +0,0 @@
1
- import { task, promptTablesConflicts, promptColumnsConflicts } from 'cli/components-api';
2
- import fs from 'fs';
3
- import * as differ from '../../../../differ';
4
- import prepareMigration from 'migrationPreparator';
5
-
6
- import { prepareAddValuesToEnumJson, prepareAlterTableColumnsJson, prepareCreateEnumJson, prepareCreateIndexesJson, prepareCreateTableJson, prepareDropIndexesJson, prepareDropTableJson, prepareRenameTableJson } from '../../../../jsonStatements';
7
- import { fromJson } from '../../../../sqlgenerator';
8
-
9
- export interface TablesResultData<T> {
10
- created: T[],
11
- renamed: RenamedObject<T>[],
12
- deleted: T[],
13
- }
14
-
15
- export interface ColumnsResultData<T extends Named> {
16
- created: T[],
17
- renamed: RenamedObject<T>[],
18
- deleted: T[],
19
- }
20
-
21
- export interface Named {
22
- name: string
23
- }
24
-
25
- export interface RenamedObject<T> {
26
- old: T,
27
- new: T
28
- }
29
-
30
- const two = (num: number) => {
31
- return num.toString().padStart(2, '0')
32
- }
33
-
34
- const migrate = async () => {
35
- const timeoutE = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)).then(() => {
36
- throw new Error('Checking error handling');
37
- });
38
-
39
- const timeout = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
40
-
41
- const migrationRootFolder = 'drizzle' // or from config/params
42
- const { prev, cur } = await task('preparing data schema json snapshot', async ({ setTitle }) => {
43
- return prepareMigration(migrationRootFolder, './data/v2')
44
- });
45
-
46
- // const j1 = JSON.parse(fs.readFileSync('./out/v1_1634546745488.json', 'utf8'));
47
- // const j2 = JSON.parse(fs.readFileSync('./out/v2_1634549601361.json', 'utf8'));
48
-
49
- const diff = await task('preparing schemas diff', async ({ setTitle }) => {
50
- return differ.differ(prev, cur);
51
- });
52
-
53
- const { created, renamed, deleted } = await promptTablesConflicts({
54
- newTables: diff.addedTables,
55
- missingTables: diff.deletedTables,
56
- });
57
-
58
- const jsonStatements: any[] = []
59
-
60
- const jsonCreateTables = created.map(it => {
61
- return prepareCreateTableJson(it)
62
- })
63
-
64
- const jsonCreateIndexesForCreatedTables = created.map(it => {
65
- return prepareCreateIndexesJson(it.name, it.indexes)
66
- }).flat()
67
-
68
- const jsonDropTables = deleted.map(it => {
69
- return prepareDropTableJson(it)
70
- })
71
-
72
- const jsonRenameTables = renamed.map(it => {
73
- return prepareRenameTableJson(it.old, it.new)
74
- })
75
-
76
- // const createNewTables = created.map(it => {
77
- // return prepareCreateTable(it)
78
- // })
79
- // console.log(createNewTables.join('\n').trim())
80
-
81
- // const deleteTables = deleted.map(it => {
82
- // return prepareDropTable(it)
83
- // })
84
- // console.log(deleteTables.join('\n').trim())
85
-
86
- const renamedWithAlternations = differ.diffForRenamed(renamed)
87
- const allAltered = diff.alteredTablesWithColumns.concat(renamedWithAlternations)
88
-
89
- const allAlteredResolved = []
90
- for (const table of allAltered) {
91
- const result = await promptColumnsConflicts(table);
92
-
93
- const { deleted, added, ...ini } = table
94
-
95
- allAlteredResolved.push({ ...ini, ...result })
96
- }
97
-
98
- // console.log(JSON.stringify(allAlteredResolved, null, 2))
99
-
100
- // const renameTables = renamed.map(it => {
101
- // return prepareRenameTable(it.from, it.to)
102
- // })
103
- // console.log(renameTables.join('\n').trim())
104
-
105
- const jsonAlterTables = allAlteredResolved.map(it => {
106
- return prepareAlterTableColumnsJson(it)
107
- }).flat()
108
-
109
- const jsonCreateIndexesForAllAlteredTables = allAlteredResolved.map(it => {
110
- return prepareCreateIndexesJson(it.name, it.addedIndexes || {})
111
- }).flat()
112
-
113
- const jsonDropIndexesForAllAlteredTables = allAlteredResolved.map(it => {
114
- return prepareDropIndexesJson(it.name, it.deletedIndexes || {})
115
- }).flat()
116
-
117
- // // Enums:
118
- // // - создание енама ✅
119
- // // - переименование енама (пока не делаю)⏳
120
- // // - добавление вэлью к енаму ✅
121
- // // - ренейм вейлью у енама (пока не делаю, это надо запрашивать опять же через слай)⏳
122
- // // - удаление енама -> чекать не используется ли где-то енам и сначала ранить миграции и в самом конце удаление енама⏳
123
- // // - удаление вэлью из енама -> блок ❌
124
- // const enums = result.addedEnums.map(it => {
125
- // return prepareCreateEnum(it.name, it.values)
126
- // })
127
-
128
- const createEnums = diff.addedEnums.map(it => {
129
- return prepareCreateEnumJson(it.name, it.values)
130
- })
131
-
132
- //todo: block enum rename, enum value rename and enun deletion for now
133
- const jsonAlterEnumsWithAddedValues = diff.alteredEnums.map(it => {
134
- return prepareAddValuesToEnumJson(it.name, it.addedValues)
135
- }).flat()
136
-
137
- jsonStatements.push(...createEnums)
138
- jsonStatements.push(...jsonAlterEnumsWithAddedValues)
139
- jsonStatements.push(...jsonCreateTables)
140
- jsonStatements.push(...jsonCreateIndexesForCreatedTables)
141
- jsonStatements.push(...jsonDropTables)
142
- jsonStatements.push(...jsonRenameTables)
143
- jsonStatements.push(...jsonAlterTables)
144
- jsonStatements.push(...jsonCreateIndexesForAllAlteredTables)
145
- jsonStatements.push(...jsonDropIndexesForAllAlteredTables)
146
-
147
- // console.log(JSON.stringify(jsonStatements, null, 2))
148
- // console.log(jsonStatements)
149
-
150
- const sqlStatements = fromJson(jsonStatements)
151
- console.log(sqlStatements.join('\n'))
152
-
153
- // todo: save results to a new migration folder
154
- const date = new Date()
155
- // const folderName = `${date.getFullYear()}-${two(date.getMonth())}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}`
156
- const folderName = date.toISOString()
157
- const migrationFolderPath = `./${migrationRootFolder}/${folderName}`
158
- fs.mkdirSync(migrationFolderPath)
159
- fs.writeFileSync(`${migrationFolderPath}/snapshot.json`, JSON.stringify(cur, null, 2))
160
- fs.writeFileSync(`${migrationFolderPath}/migration.sql`, sqlStatements.join('\n'))
161
-
162
- };
163
-
164
- export default migrate;
@@ -1,20 +0,0 @@
1
- import React from 'react';
2
- import { useSnapshot } from 'valtio';
3
-
4
- interface Props {
5
- componentsList: React.ReactElement<any, any>[];
6
- }
7
-
8
- const ComponentsList: React.FC<Props> = ({
9
- componentsList,
10
- }) => {
11
- useSnapshot(componentsList);
12
-
13
- return (
14
- <>
15
- {componentsList.map((component, i) => ({ ...component, key: i }))}
16
- </>
17
- );
18
- };
19
-
20
- export default ComponentsList;
@@ -1,19 +0,0 @@
1
- import { render } from 'ink';
2
- import React from 'react';
3
-
4
- import ComponentsList from 'cli/components-api/ComponentsList';
5
-
6
- const createApp = (componentsList: React.ReactElement<any, any>[]) => {
7
- const inkApp = render(<ComponentsList componentsList={componentsList} />);
8
-
9
- return {
10
- remove() {
11
- inkApp.rerender(null);
12
- inkApp.unmount();
13
- inkApp.clear();
14
- inkApp.cleanup();
15
- },
16
- };
17
- };
18
-
19
- export default createApp;
@@ -1,171 +0,0 @@
1
- import React from 'react';
2
- import { Box, Text } from 'ink';
3
- import SelectInput from 'ink-select-input';
4
- import Table, { Header } from 'ink-table';
5
- import { useMachine } from '@xstate/react';
6
- import { Item } from 'ink-select-input/build/SelectInput';
7
-
8
- import { ColumnsResultData, Named } from 'cli/commands/migration/migrate';
9
- import formatDataForTable from 'cli/utils/formatDataForTable';
10
- import {
11
- Action,
12
- Confirmation,
13
- actions,
14
- confirmations,
15
- } from 'cli/utils/valuesForPrompts';
16
- import createResolveColumnsMachine, { TableWithColumn } from 'cli/machines/resolveColumnsMachine';
17
-
18
- interface Props {
19
- onDone: (value: ColumnsResultData<Named>) => void
20
- tableWithColumns: TableWithColumn,
21
- }
22
-
23
- const PromptColumnsConflicts: React.FC<Props> = ({
24
- onDone,
25
- tableWithColumns: props,
26
- }) => {
27
- const [current, send] = useMachine(
28
- createResolveColumnsMachine({ tableWithColumns: props }),
29
- );
30
-
31
- const {
32
- tableName,
33
- addedColumns,
34
- deletedColumns,
35
- missingItemIndex,
36
- created,
37
- renamed,
38
- deleted,
39
- } = current.context;
40
-
41
- const selectItemIndex = (item: Item<number>) => {
42
- send({ type: 'CHOICE_ITEM', itemIndex: item.value });
43
- };
44
-
45
- const selectNewItemIndex = (item: Item<number>) => {
46
- send({ type: 'CHOICE_NEW_ITEM', itemIndex: item.value });
47
- };
48
-
49
- const selectAction = (action: Item<Action>) => {
50
- send({ type: action.value });
51
- };
52
-
53
- const confirm = (confirmationItem: Item<Confirmation>) => {
54
- send({ type: confirmationItem.value });
55
- };
56
-
57
- const renderDOM = () => {
58
- if (current.matches('table')) {
59
- return (
60
- <>
61
- <Box display="flex" flexDirection="column">
62
- <Box display="flex">
63
- <Box flexDirection="column">
64
- <Header>{`Table "${tableName}" missing columns:`}</Header>
65
- <SelectInput
66
- items={deletedColumns!.map((column, i: number) => ({
67
- key: String(i),
68
- label: column.name,
69
- value: i,
70
- }))}
71
- onSelect={selectItemIndex}
72
- />
73
- </Box>
74
- {!!addedColumns?.length && (
75
- <Box flexDirection="column" paddingLeft={5}>
76
- <Header>New tables:</Header>
77
- <Box display="flex" flexDirection="column">
78
- {addedColumns.map(({ name }, i) => <Text key={name + i}>{name}</Text>)}
79
- </Box>
80
- </Box>
81
- )}
82
- </Box>
83
- </Box>
84
- </>
85
- );
86
- }
87
-
88
- if (current.matches('action.actionChoice')) {
89
- const tempActions = !addedColumns!.length
90
- ? actions.filter(({ value }) => value !== Action.RENAME)
91
- : actions;
92
-
93
- return (
94
- <>
95
- <Header>{`${deletedColumns![missingItemIndex]?.name} is:`}</Header>
96
- <SelectInput items={tempActions} onSelect={selectAction} />
97
- </>
98
- );
99
- }
100
-
101
- if (current.matches('confirmationDelete')) {
102
- return (
103
- <>
104
- <Header>!!! Data in table will be lost !!!</Header>
105
- <Text>Are you sure?</Text>
106
- <SelectInput items={confirmations} onSelect={confirm} />
107
- </>
108
- );
109
- }
110
-
111
- if (current.matches('confirmationRename')) {
112
- return (
113
- <>
114
- <Header>Are you sure?</Header>
115
- <SelectInput items={confirmations} onSelect={confirm} />
116
- </>
117
- );
118
- }
119
-
120
- if (current.matches('action.rename')) {
121
- return (
122
- <>
123
- <Header>{`${deletedColumns![missingItemIndex]?.name} was renamed to:`}</Header>
124
- <SelectInput
125
- items={addedColumns!.map((table, i: number) => ({
126
- key: String(i),
127
- label: table.name,
128
- value: i,
129
- }))}
130
- onSelect={selectNewItemIndex}
131
- />
132
- </>
133
- );
134
- }
135
-
136
- if (current.matches('done')) {
137
- onDone({ created, renamed, deleted });
138
- }
139
-
140
- return (<></>);
141
- };
142
-
143
- return (!!deleted.length
144
- || !!renamed.length
145
- || !!created.length) ? (
146
- <Box flexDirection="column" margin={1}>
147
- <Box flexDirection="column" marginBottom={0}>
148
- <Header>{`${tableName} columns:`}</Header>
149
- <Table
150
- data={formatDataForTable([
151
- {
152
- title: 'Deleted',
153
- values: deleted,
154
- },
155
- {
156
- title: 'Renamed',
157
- values: renamed,
158
- },
159
- {
160
- title: 'Created',
161
- values: created,
162
- },
163
- ])}
164
- />
165
- </Box>
166
- {renderDOM()}
167
- </Box>
168
- ) : renderDOM();
169
- };
170
-
171
- export default PromptColumnsConflicts;