@@ -5,6 +5,8 @@ import yargs from 'yargs/yargs'
5
5
import { hideBin } from 'yargs/helpers'
6
6
import { cosmiconfig } from 'cosmiconfig'
7
7
import Confirm from 'prompt-confirm'
8
+ import SqliteDatabase from 'better-sqlite3'
9
+ import mysql from 'mysql2/promise'
8
10
import sqldef from './index.js'
9
11
10
12
// get a reasonable port
@@ -24,7 +26,36 @@ const getPort = (args) => {
24
26
25
27
// get the current structure of database, as text
26
28
async function getStructure ( { type, host, database, user, password, socket, port } ) {
27
- console . log ( { type, host, database, user, password, socket, port } )
29
+ if ( type === 'sqlite' ) {
30
+ const db = new SqliteDatabase ( host )
31
+ const tables = db . prepare ( 'SELECT sql FROM sqlite_master WHERE type = "table" AND name NOT LIKE "sqlite_%"' ) . all ( )
32
+ return tables . map ( ( t ) => t . sql ) . join ( ';\n' ) + ';'
33
+ } else if ( type === 'mysql' ) {
34
+ const connection = await mysql . createConnection ( {
35
+ host,
36
+ user,
37
+ password,
38
+ database,
39
+ socket,
40
+ port
41
+ } )
42
+ const [ tables ] = await connection . query ( 'SELECT table_name FROM information_schema.tables WHERE table_schema = ?' , [ database ] )
43
+ return (
44
+ (
45
+ await Promise . all (
46
+ tables . map ( async ( table ) => {
47
+ const tableName = table . table_name
48
+ const [ result ] = await connection . query ( `SHOW CREATE TABLE \`${ tableName } \`` )
49
+ if ( result && result [ 0 ] ) {
50
+ return result [ 0 ] [ 'Create Table' ]
51
+ } else {
52
+ return ''
53
+ }
54
+ } )
55
+ )
56
+ ) . join ( ';\n' ) + ';'
57
+ )
58
+ }
28
59
}
29
60
30
61
// export the current database as a file
@@ -36,8 +67,10 @@ async function handleExport({ file, type, host, database, user, password, socket
36
67
// import database from file (using diff)
37
68
async function handleImport ( { newStruct, type, host, database, user, password, socket, port, dry = false } ) {
38
69
const current = await getStructure ( { type, host, database, user, password, socket, port } )
70
+ const diff = await sqldef ( type , current , newStruct )
39
71
if ( dry ) {
40
- console . log ( 'dry' )
72
+ console . log ( diff )
73
+ return
41
74
}
42
75
}
43
76
@@ -101,7 +134,7 @@ yargs(hideBin(process.argv))
101
134
102
135
. option ( 'h' , {
103
136
alias : 'host' ,
104
- describe : 'The host of the database' ,
137
+ describe : 'The host (or filename for sqlite) of the database' ,
105
138
nargs : 1 ,
106
139
default : config . host || 'localhost'
107
140
} )
0 commit comments