Skip to content

Instantly share code, notes, and snippets.

@johndstein
Last active August 30, 2017 22:19
Show Gist options
  • Save johndstein/f4807161e3223fc05d5d23d8eb1a2b8f to your computer and use it in GitHub Desktop.
Save johndstein/f4807161e3223fc05d5d23d8eb1a2b8f to your computer and use it in GitHub Desktop.
SQL Server Handle Image Data Type
// So this guy will pull down a bunch of word docs from SQL server
// and write them out to file.
// woo hoo.
const sql = require('mssql/msnodesqlv8');
const fs = require('fs');
const path = require('path');
const {promisify} = require('util');
const rimraf = promisify(require('rimraf'));
const mkdir = promisify(fs.mkdir);
// const writeFile = promisify(fs.writeFile);
// const appendFile = promisify(fs.appendFile);
async function cleanup() {
try {
await rimraf('docs');
await mkdir('docs');
} catch (err) {
console.error('ERROR', err);
process.exit(11);
}
}
async function initPool() {
try {
return await sql.connect({
driver: 'msnodesqlv8',
server: 'LEAH',
database: 'WycliffeProduction',
stream: true, // You can enable streaming globally or per request
options: {
trustedConnection: true,
encrypt: true
}
});
} catch (err) {
console.error('ERROR', err);
process.exit(11);
}
}
async function doQuery() {
try {
const result = await sql.query`
select
c.id,
a.worddocname,
a.worddoc
from
actions a
join re_reporter.dbo.sf_contact c
on c.re_legacy_id__c = a.records_id
where
worddoc is not null
order by
c.id,
a.worddocname`;
return result;
} catch (err) {
console.error('ERROR', err);
process.exit(11);
}
}
let curId = null;
let curName = null;
let i = 0;
function cleanName(name) {
if (!name) {
return `NO_NAME${i++}`;
}
return name.replace(/\W+/g, '_');
}
function handleFile(rs, wd) {
let name = cleanName(rs.worddocname);
if (curId != rs.id) {
curId = rs.id;
curName = name;
fs.mkdirSync(path.join('docs', rs.id));
fs.writeFileSync(path.join('docs', rs.id, name + '.doc'), wd);
} else if (curName != name) {
curName = name;
fs.writeFileSync(path.join('docs', rs.id, name + '.doc'), wd);
} else {
fs.appendFileSync(path.join('docs', rs.id, name + '.doc'), wd);
}
}
async function doit() {
await cleanup();
const pool = await initPool();
const result = await doQuery();
result.recordset.forEach((rs) => {
rs.worddoc.forEach((wd) => {
handleFile(rs, wd);
});
});
pool.close();
}
doit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment