Skip to content

Commit 6b4abd4

Browse files
committed
Basic implementation
0 parents  commit 6b4abd4

15 files changed

+6446
-0
lines changed

.eslintrc

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
{
2+
"ignorePatterns": ["/node_modules/", "/dist/"],
3+
"parserOptions": {
4+
"ecmaVersion": 2019
5+
},
6+
"env": {
7+
"node": true,
8+
"jest": true
9+
},
10+
"extends": ["eslint:recommended", "prettier"],
11+
"overrides": [
12+
{
13+
"files": ["*.{ts,tsx}"],
14+
"parser": "@typescript-eslint/parser",
15+
"parserOptions": {
16+
"project": "./tsconfig.json"
17+
},
18+
"extends": [
19+
"plugin:@typescript-eslint/eslint-recommended",
20+
"plugin:@typescript-eslint/recommended",
21+
"plugin:@typescript-eslint/recommended-requiring-type-checking",
22+
"prettier/@typescript-eslint"
23+
],
24+
"rules": {
25+
"@typescript-eslint/no-unused-vars": "off",
26+
"@typescript-eslint/no-floating-promises": "error",
27+
"@typescript-eslint/camelcase": "off",
28+
"@typescript-eslint/require-await": "off"
29+
}
30+
}
31+
]
32+
}

.gitignore

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
8+
# Runtime data
9+
pids
10+
*.pid
11+
*.seed
12+
*.pid.lock
13+
14+
# Directory for instrumented libs generated by jscoverage/JSCover
15+
lib-cov
16+
17+
# Coverage directory used by tools like istanbul
18+
coverage
19+
20+
# nyc test coverage
21+
.nyc_output
22+
23+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24+
.grunt
25+
26+
# Bower dependency directory (https://bower.io/)
27+
bower_components
28+
29+
# node-waf configuration
30+
.lock-wscript
31+
32+
# Compiled binary addons (http://nodejs.org/api/addons.html)
33+
build/Release
34+
35+
# Dependency directories
36+
node_modules/
37+
jspm_packages/
38+
39+
# Typescript v1 declaration files
40+
typings/
41+
42+
# Optional npm cache directory
43+
.npm
44+
45+
# Optional eslint cache
46+
.eslintcache
47+
48+
# Optional REPL history
49+
.node_repl_history
50+
51+
# Output of 'npm pack'
52+
*.tgz
53+
54+
# Yarn Integrity file
55+
.yarn-integrity
56+
57+
# dotenv environment variables file
58+
.env
59+
60+
/migrations
61+
/dist

README.md

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# postgres-schema-ts
2+
3+
> postgres-schema-ts is a simple npm module you can use to convert a mysql schema into typescript interfaces
4+
5+
# Usage
6+
7+
```bash
8+
# to infer an entire schema
9+
$ npx postgres-schema-ts mysql://root@localhost:3306/database
10+
11+
# to infer a specific table
12+
$ npx postgres-schema-ts mysql://root@localhost:3306/database table_name
13+
```
14+
15+
tip: You can pipe the output of postgres-schema-ts into a file with `npx postgres-schema-ts <args> > schema.ts`
16+
17+
## Demo
18+
19+
For the following SQL schema: (from the musicbrainz database)
20+
21+
```sql
22+
CREATE TABLE IF NOT EXISTS artist ( -- replicate (verbose)
23+
id SERIAL,
24+
gid CHAR(36) NOT NULL,
25+
name VARCHAR(255) NOT NULL,
26+
sort_name VARCHAR(255) NOT NULL,
27+
begin_date_year SMALLINT,
28+
begin_date_month SMALLINT,
29+
begin_date_day SMALLINT,
30+
end_date_year SMALLINT,
31+
end_date_month SMALLINT,
32+
end_date_day SMALLINT,
33+
type INTEGER, -- references artist_type.id
34+
area INTEGER, -- references area.id
35+
gender INTEGER, -- references gender.id
36+
comment VARCHAR(255) NOT NULL DEFAULT '',
37+
edits_pending INTEGER NOT NULL DEFAULT 0 CHECK (edits_pending >= 0),
38+
last_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
39+
ended CHAR(1) NOT NULL DEFAULT FALSE
40+
);
41+
42+
CREATE TABLE IF NOT EXISTS track ( -- replicate (verbose)
43+
id SERIAL,
44+
gid CHAR(36) NOT NULL,
45+
recording INTEGER NOT NULL, -- references recording.id
46+
medium INTEGER NOT NULL, -- references medium.id
47+
position INTEGER NOT NULL,
48+
number TEXT NOT NULL,
49+
name VARCHAR(255) NOT NULL,
50+
artist_credit INTEGER NOT NULL, -- references artist_credit.id
51+
length INTEGER CHECK (length IS NULL OR length > 0),
52+
edits_pending INTEGER NOT NULL DEFAULT 0 CHECK (edits_pending >= 0),
53+
last_updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
54+
is_data_track CHAR(1) NOT NULL DEFAULT FALSE
55+
) CHARACTER SET utf8 COLLATE utf8_general_ci;
56+
```
57+
58+
run:
59+
60+
```bash
61+
$ npx postgres-schema-ts mysql://root@localhost:3306/musicbrainz
62+
```
63+
64+
```typescript
65+
export interface artist {
66+
id: number
67+
gid: string
68+
name: string
69+
sort_name: string
70+
begin_date_year: number | null
71+
begin_date_month: number | null
72+
begin_date_day: number | null
73+
end_date_year: number | null
74+
end_date_month: number | null
75+
end_date_day: number | null
76+
type: number | null
77+
area: number | null
78+
gender: number | null
79+
comment: string
80+
edits_pending: number
81+
last_updated: Date
82+
ended: string
83+
}
84+
export interface track {
85+
id: number
86+
gid: string
87+
recording: number
88+
medium: number
89+
position: number
90+
number_: string
91+
name: string
92+
artist_credit: number
93+
length: number | null
94+
edits_pending: number
95+
last_updated: Date
96+
is_data_track: string
97+
}
98+
```
99+
100+
## Using `postgres-schema-ts` programatically
101+
102+
```typescript
103+
import { inferSchema, inferTable } from 'postgres-schema-ts'
104+
105+
await inferSchema(connectionString)
106+
await inferTable(connectionString, tableName)
107+
```
108+
109+
## Design
110+
111+
postgres-schema-ts is inpired by the awesome [schemats](https://github.com/SweetIQ/schemats) library.
112+
But takes a simpler, more blunt, and configuration free approach:
113+
114+
- Simpler defaults
115+
- MySQL support only
116+
- Inline enums
117+
- No support for namespaces
118+
119+
## License (MIT)
120+
121+
```
122+
WWWWWW||WWWWWW
123+
W W W||W W W
124+
||
125+
( OO )__________
126+
/ | \
127+
/o o| MIT \
128+
\___/||_||__||_|| *
129+
|| || || ||
130+
_||_|| _||_||
131+
(__|__|(__|__|
132+
```
133+
134+
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:
135+
136+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
137+
138+
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.

__tests__/index.test.ts

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import { Postgres } from '../src/pg-client'
2+
import { inferTable, inferSchema } from '../src'
3+
import { SQL as sql } from 'sql-template-strings'
4+
5+
const connectionString = 'postgresql://postgres@localhost:5433/db?currentSchema=public'
6+
const pg = new Postgres(connectionString)
7+
8+
const account = sql`
9+
DROP TABLE IF EXISTS account;
10+
CREATE TABLE account (
11+
username VARCHAR (50) UNIQUE NOT NULL,
12+
password VARCHAR (50) NOT NULL,
13+
email VARCHAR (355) UNIQUE NOT NULL,
14+
created_on TIMESTAMP NOT NULL,
15+
last_login TIMESTAMP
16+
)
17+
`
18+
19+
const requests = sql`
20+
DROP TYPE IF EXISTS integration_type_enum CASCADE;
21+
CREATE TYPE integration_type_enum AS ENUM (
22+
'source',
23+
'destination'
24+
);
25+
26+
DROP TABLE IF EXISTS requests;
27+
CREATE TABLE requests (
28+
name varchar(255) NOT NULL,
29+
url varchar(255) NOT NULL,
30+
integration_type integration_type_enum NOT NULL
31+
);
32+
`
33+
34+
const complex = sql`
35+
DROP TABLE IF EXISTS complex;
36+
CREATE TABLE complex (
37+
id json NOT NULL,
38+
name varchar(255) NOT NULL,
39+
nullable varchar(255),
40+
created_at timestamp,
41+
created_on date NOT NULL
42+
)
43+
`
44+
45+
beforeAll(async () => {
46+
await pg.query(account)
47+
await pg.query(requests)
48+
await pg.query(complex)
49+
})
50+
51+
describe('inferTable', () => {
52+
it('infers a table', async () => {
53+
const code = await inferTable(connectionString, 'account')
54+
expect(code).toMatchInlineSnapshot(`
55+
"export interface account {
56+
username: string
57+
password: string
58+
email: string
59+
created_on: Date
60+
last_login: Date | null
61+
}
62+
"
63+
`)
64+
})
65+
66+
it('works with enums', async () => {
67+
const code = await inferTable(connectionString, 'requests')
68+
expect(code).toMatchInlineSnapshot(`
69+
"export interface requests {
70+
name: string
71+
url: string
72+
integration_type: 'destination' | 'source'
73+
}
74+
"
75+
`)
76+
})
77+
78+
it('works with complex types', async () => {
79+
const code = await inferTable(connectionString, 'complex')
80+
expect(code).toMatchInlineSnapshot(`
81+
"export interface complex {
82+
id: Object
83+
name: string
84+
nullable: string | null
85+
created_at: Date | null
86+
created_on: Date
87+
}
88+
"
89+
`)
90+
})
91+
})
92+
93+
describe('inferSchema', () => {
94+
it('infers all tables at once', async () => {
95+
const code = await inferSchema(connectionString)
96+
expect(code).toMatchInlineSnapshot(`
97+
"export interface account {
98+
username: string
99+
password: string
100+
email: string
101+
created_on: Date
102+
last_login: Date | null
103+
}
104+
export interface complex {
105+
id: Object
106+
name: string
107+
nullable: string | null
108+
created_at: Date | null
109+
created_on: Date
110+
}
111+
export interface requests {
112+
name: string
113+
url: string
114+
integration_type: 'destination' | 'source'
115+
}
116+
"
117+
`)
118+
})
119+
})

bin/index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/usr/bin/env node
2+
import { inferSchema, inferTable } from '../src'
3+
4+
const [...args] = process.argv
5+
6+
async function main(): Promise<string> {
7+
const db = args[2] || ''
8+
const table = args[3]
9+
10+
if (table) {
11+
return inferTable(db, table)
12+
}
13+
14+
return inferSchema(db)
15+
}
16+
17+
main()
18+
.then(code => {
19+
console.log(code)
20+
process.exit()
21+
})
22+
.catch(err => {
23+
console.error(err)
24+
process.exit(1)
25+
})

docker-compose.yml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
postgres:
2+
image: postgres:9.6
3+
ports:
4+
- '5433:5432'
5+
environment:
6+
POSTGRES_DB: 'db'
7+
8+
musicbrainz:
9+
image: arey/musicbrainz-database
10+
ports:
11+
- '5434:5432'

jest-setup.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
export default async function jestSetup(): Promise<void> {
2+
// Automatically configure the tests to connect to the test DB
3+
}

0 commit comments

Comments
 (0)