Skip to content

Commit f5c835d

Browse files
committed
stubbing cli
1 parent 7ba8b01 commit f5c835d

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

cli.mjs

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import yargs from 'yargs/yargs'
55
import { hideBin } from 'yargs/helpers'
66
import { cosmiconfig } from 'cosmiconfig'
77
import Confirm from 'prompt-confirm'
8+
import SqliteDatabase from 'better-sqlite3'
9+
import mysql from 'mysql2/promise'
810
import sqldef from './index.js'
911

1012
// get a reasonable port
@@ -24,7 +26,36 @@ const getPort = (args) => {
2426

2527
// get the current structure of database, as text
2628
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+
}
2859
}
2960

3061
// export the current database as a file
@@ -36,8 +67,10 @@ async function handleExport({ file, type, host, database, user, password, socket
3667
// import database from file (using diff)
3768
async function handleImport({ newStruct, type, host, database, user, password, socket, port, dry = false }) {
3869
const current = await getStructure({ type, host, database, user, password, socket, port })
70+
const diff = await sqldef(type, current, newStruct)
3971
if (dry) {
40-
console.log('dry')
72+
console.log(diff)
73+
return
4174
}
4275
}
4376

@@ -101,7 +134,7 @@ yargs(hideBin(process.argv))
101134

102135
.option('h', {
103136
alias: 'host',
104-
describe: 'The host of the database',
137+
describe: 'The host (or filename for sqlite) of the database',
105138
nargs: 1,
106139
default: config.host || 'localhost'
107140
})

0 commit comments

Comments
 (0)