25 lines
14 KiB
JavaScript
25 lines
14 KiB
JavaScript
"use strict";exports.id=2451,exports.ids=[2451],exports.modules={48225:(e,a,t)=>{let l=t(29021),{IncomingMessage:r}=t(81630);e.exports=async function({user:e,message:a,component:t,noMail:r,req:i}){let n=new Date,d=(()=>{if(!i)return null;try{let e=i.headers["x-forwarded-for"],a=i.headers["x-real-ip"],t=i.headers["cf-connecting-ip"],l=Array.isArray(e)?e[0]:e?.split(",")[0],r=t||l||a||i.socket.remoteAddress;if(!r)return null;return String(r)}catch(e){return null}})();try{let r=`🚀 SERVER ERROR ===========================
|
|
Error Message: ${a}
|
|
Component: ${t}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(r+=`
|
|
User Id: ${e?.id}
|
|
User Name: ${e?.first_name} ${e?.last_name}
|
|
User Email: ${e?.email}`),i?.url&&(r+=`
|
|
URL: ${i.url}`),i?.body&&(r+=`
|
|
Request Body: ${JSON.stringify(i.body,null,4)}`),d&&(r+=`
|
|
IP: ${d}`),r+=`
|
|
Date: ${n.toDateString()}
|
|
========================================`,l.existsSync("./.tmp/error.log")||l.writeFileSync("./.tmp/error.log","","utf-8");let s=l.readFileSync("./.tmp/error.log","utf-8");l.writeFileSync("./.tmp/error.log",r),l.appendFileSync("./.tmp/error.log",`
|
|
|
|
|
|
|
|
|
|
${s}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},72835:(e,a,t)=>{let{scryptSync:l,createDecipheriv:r}=t(55511),{Buffer:i}=t(79428);e.exports=({encryptedString:e,encryptionKey:a,encryptionSalt:t})=>{if(!e?.match(/./))return console.log("Encrypted string is invalid"),e;let n=a||process.env.DSQL_ENCRYPTION_PASSWORD,d=t||process.env.DSQL_ENCRYPTION_SALT,s=process.env.DSQL_ENCRYPTION_KEY_LENGTH?Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH):24;if(!n?.match(/.{8,}/))return console.log("Decrption key is invalid"),e;if(!d?.match(/.{8,}/))return console.log("Decrption salt is invalid"),e;let o=r("aes-192-cbc",l(n,d,s),i.alloc(16,0));try{let a=o.update(e,"hex","utf8");return a+=o.final("utf8")}catch(a){return console.log("Error in decrypting =>",a.message),e}}},19261:(e,a,t)=>{let l=t(33873),r=t(29021);t(60818).config({path:"./../.env"});let i=t(3444),n=t(38864),d=t(12452),s=t(35031),o=t(16926),u=t(27836),E=process.argv.find(e=>"--exec"===e);async function c({userId:e,targetDatabase:a,dbSchemaData:t}){let E=e?l.join(String(process.env.DSQL_USER_DB_SCHEMA_PATH),`/user-${e}/main.json`):l.resolve(__dirname,"../../jsonData/dbSchemas/main.json"),N=t||u.parse(r.readFileSync(E,"utf8"));if(!N){console.log("Schema Not Found!");return}for(let t=0;t<N.length;t++){let l=N[t],{dbFullName:r,tables:u,dbName:E,dbSlug:f,childrenDatabases:T}=l;if(a&&r!=a)continue;let b=await i(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${r}'`);b&&b[0]?.dbFullName||await i(`CREATE DATABASE IF NOT EXISTS \`${r}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);let m=await i(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${r}'`);for(let a=0;a<m.length;a++){let{TABLE_NAME:t}=m[a];if(!u.filter(e=>e.tableName===t)[0]){let a=u.filter(e=>e.tableNameOld&&e.tableNameOld===t);a&&a[0]?(console.log("Renaming Table"),await n({queryString:`RENAME TABLE \`${a[0].tableNameOld}\` TO \`${a[0].tableName}\``,database:r})):(console.log(`Dropping Table from ${r}`),await n({queryString:`DROP TABLE \`${t}\``,database:r}),await o({query:"DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?",values:[e,f,t],database:"datasquirel"}))}}let _=e?await n({database:"datasquirel",queryString:"SELECT * FROM user_databases WHERE db_full_name = ?",queryValuesArray:[r]}):void 0,S=_?.[0];for(let a=0;a<u.length;a++){let t=u[a],{tableName:i,fields:o,indexes:E}=t,c=await n({queryString:`
|
|
SELECT EXISTS (
|
|
SELECT
|
|
TABLE_NAME
|
|
FROM
|
|
information_schema.TABLES
|
|
WHERE
|
|
TABLE_SCHEMA = ? AND
|
|
TABLE_NAME = ?
|
|
) AS tableExists`,queryValuesArray:[r,t.tableName],database:r});if(c&&c[0]?.tableExists>0){if(await s({dbFullName:r,tableName:i,tableNameFull:t.tableFullName,tableInfoArray:o,userId:e,dbSchema:N,tableIndexes:E,tableIndex:a,childDb:l.childDatabase||void 0,recordedDbEntry:S,tableSchema:t}),t.childrenTables&&t.childrenTables[0])for(let a=0;a<t.childrenTables.length;a++){let r=t.childrenTables[a];await s({dbFullName:r.dbNameFull,tableName:r.tableName,tableNameFull:r.tableNameFull,tableInfoArray:o,userId:e,dbSchema:N,tableIndexes:E,clone:!0,childDb:l.childDatabase||void 0,recordedDbEntry:S,tableSchema:t})}}else if(await d({tableName:i,tableInfoArray:o,dbFullName:r,dbSchema:N,tableSchema:t,recordedDbEntry:S}),E&&E[0]&&E&&E[0])for(let e=0;e<E.length;e++){let{indexType:a,indexName:t,indexTableFields:l,alias:d}=E[e];if(d?.match(/./))try{if(!(await n({queryString:`SHOW INDEXES FROM \`${i}\``,database:r})).filter(e=>e.Key_name===d)[0])throw Error("This Index Does not Exist")}catch(e){await n({queryString:`CREATE${a?.match(/fullText/i)?" FULLTEXT":""} INDEX \`${d}\` ON ${i}(${l?.map(e=>e.value).map(e=>`\`${e}\``).join(",")}) COMMENT 'schema_index'`,database:r})}}}if(T?.[0])for(let a=0;a<T.length;a++){let{dbFullName:t}=T[a];await c({userId:e,targetDatabase:t})}}}e.exports=c,E&&c({})},12452:(e,a,t)=>{let l=t(38864),r=t(74941),i=t(57897),n=t(16926);e.exports=async function({dbFullName:e,tableName:a,tableInfoArray:t,dbSchema:d,clone:s,tableSchema:o,recordedDbEntry:u}){let E=i({tableInfoArray:t}),c=[];c.push(`CREATE TABLE IF NOT EXISTS \`${a}\` (`);try{if(!u)throw Error("Recorded Db entry not found!");let e=await l({database:"datasquirel",queryString:"SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?",queryValuesArray:[u.id,o?.tableName]}),a=e?.[0];a?.id||await n({query:"INSERT INTO user_database_tables SET ?",values:{user_id:u.user_id,db_id:u.id,db_slug:u.db_slug,table_name:o?.tableFullName,table_slug:o?.tableName,child_table:o?.childTable?"1":null,child_table_parent_database:o?.childTableDbFullName||null,child_table_parent_table:o?.childTableName||null,date_created:Date(),date_created_code:Date.now(),date_updated:Date(),date_updated_code:Date.now()},database:"datasquirel"})}catch(e){}let N=!1,f=[];for(let e=0;e<E.length;e++){let a=E[e],{fieldName:t,dataType:l,nullValue:i,primaryKey:n,autoIncrement:d,defaultValue:s,defaultValueLiteral:o,foreignKey:u,updatedField:T,onUpdate:b,onUpdateLiteral:m,onDelete:_,onDeleteLiteral:S,defaultField:A,encrypted:p,json:y,newTempField:g,notNullValue:R,originName:h,plainText:D,pattern:O,patternFlags:$,richText:L}=a;u&&f.push({...a});let{fieldEntryText:I,newPrimaryKeySet:C}=r({columnData:a,primaryKeySet:N});N=C;let M=f[0]?",":e===E.length-1?"":",";c.push(" "+I+M)}f[0]&&f.forEach((e,a,t)=>{let l=e.fieldName,r=e.foreignKey?.destinationTableName,i=e.foreignKey?.destinationTableColumnName,n=e.foreignKey?.cascadeDelete,d=e.foreignKey?.cascadeUpdate,s=e.foreignKey?.foreignKeyName,o=a===f.length-1?"":",";c.push(` CONSTRAINT \`${s}\` FOREIGN KEY (\`${l}\`) REFERENCES \`${r}\`(${i})${n?" ON DELETE CASCADE":""}${d?" ON UPDATE CASCADE":""}${o}`)}),c.push(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;");let T=c.join("\n");return await l({queryString:T,database:e})}},16926:(e,a,t)=>{let l=t(29021),r=t(33873),i=t(9973),n=t(21580),d=i({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:process.env.DSQL_DB_NAME,charset:"utf8mb4",ssl:n()}});e.exports=async function({query:e,values:a,database:t}){let s;t&&(d=i({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:t,charset:"utf8mb4",ssl:n()}}));try{s=e&&a?await d.query(e,a):await d.query(e),await d.end()}catch(e){if(process.env.FIRST_RUN)return null;console.log("ERROR in dbHandler =>",e.message),console.log(e),console.log(d.config()),l.appendFileSync(r.resolve(__dirname,"../.tmp/dbErrorLogs.txt"),JSON.stringify(e,null,4)+"\n"+Date()+"\n\n\n","utf8"),s=null}return s?JSON.parse(JSON.stringify(s)):null}},74941:e=>{e.exports=function({columnData:e,primaryKeySet:a}){let{fieldName:t,dataType:l,nullValue:r,primaryKey:i,autoIncrement:n,defaultValue:d,defaultValueLiteral:s,foreignKey:o,updatedField:u,onUpdate:E,onUpdateLiteral:c,onDelete:N,onDeleteLiteral:f,defaultField:T,encrypted:b,json:m,newTempField:_,notNullValue:S,originName:A,plainText:p,pattern:y,patternFlags:g,richText:R}=e,h="";return h+=`\`${t}\` ${l}`,r?h+=" DEFAULT NULL":s?h+=` DEFAULT ${s}`:d?String(d).match(/uuid\(\)/i)?h+=" DEFAULT UUID()":h+=` DEFAULT '${d}'`:S&&(h+=" NOT NULL"),c&&(h+=` ON UPDATE ${c}`),i&&!a&&(h+=" PRIMARY KEY",a=!0),n&&(h+=" AUTO_INCREMENT",a=!0),{fieldEntryText:h,newPrimaryKeySet:a||!1}}},3444:(e,a,t)=>{let l=t(16926);e.exports=async function(e){let a;try{a=await l({query:e})}catch(e){console.log("ERROR in noDatabaseDbHandler =>",e.message)}return a||null}},57897:(e,a,t)=>{e.exports=function({tableInfoArray:e}){let a=t(95610),l=e.filter(e=>e.primaryKey);return a.forEach(a=>{let t=e.filter(e=>e.fieldName===a.fieldName);t&&t[0]||("id"!==a.fieldName||l[0]?e.push(a):e.unshift(a))}),e}},35031:(e,a,t)=>{let l=t(29021),r=t(38864),i=/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/,n=t(74941),d=t(16926);e.exports=async function({dbFullName:e,tableName:a,tableInfoArray:t,userId:s,dbSchema:o,tableIndexes:u,tableSchema:E,clone:c,childDb:N,tableIndex:f,tableNameFull:T,recordedDbEntry:b}){let m=[],_=t;try{let t=[];if(t.push(`ALTER TABLE \`${a}\``),N)try{if(!b)throw Error("Recorded Db entry not found!");let e=await r({database:"datasquirel",queryString:"SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?",queryValuesArray:[b.id,a]}),t=e?.[0];t?.id||await d({query:"INSERT INTO user_database_tables SET ?",values:{user_id:b.user_id,db_id:b.id,db_slug:b.db_slug,table_name:T,table_slug:a,child_table:E?.childTable?"1":null,child_table_parent_database:E?.childTableDbFullName||null,child_table_parent_table:E.childTableName||null,date_created:Date(),date_created_code:Date.now(),date_updated:Date(),date_updated_code:Date.now()},database:"datasquirel"})}catch(e){}let f=await r({queryString:`SHOW INDEXES FROM \`${a}\``,database:e}),S=await r({queryString:`SHOW COLUMNS FROM \`${a}\``,database:e}),A=[];for(let t=0;t<S.length;t++){let{Field:n}=S[t];if(n.match(i))continue;let d=_.filter(e=>e.fieldName===n||e.originName===n);if(d&&d[0]){if(d[0].updatedField&&d[0].fieldName){A.push(d[0].fieldName),await r({queryString:`ALTER TABLE ${a} RENAME COLUMN \`${d[0].originName}\` TO \`${d[0].fieldName}\``,database:e}),console.log(`Column Renamed from "${d[0].originName}" to "${d[0].fieldName}"`);try{let t=o.findIndex(a=>a.dbFullName===e),r=o[t].tables.findIndex(e=>e.tableName===a),i=o[t].tables[r].fields.findIndex(e=>e.fieldName===d[0].fieldName);delete o[t].tables[r].fields[i].originName,delete o[t].tables[r].fields[i].updatedField,_=o[t].tables[r].fields,l.writeFileSync(`${String(process.env.DSQL_USER_DB_SCHEMA_PATH)}/user-${s}/main.json`,JSON.stringify(o),"utf8")}catch(e){console.log("Update table error =>",e.message)}}continue}await r({queryString:`ALTER TABLE ${a} DROP COLUMN \`${n}\``,database:e})}for(let t=0;t<f.length;t++){let{Key_name:l,Index_comment:i}=f[t];if(i?.match(/schema_index/))try{let e=u?.filter(e=>e.alias===l);if(!e?.[0])throw Error(`This Index(${l}) Has been Deleted!`)}catch(t){await r({queryString:`ALTER TABLE ${a} DROP INDEX \`${l}\``,database:e})}}if(u&&u[0])for(let t=0;t<u.length;t++){let{indexType:l,indexName:i,indexTableFields:n,alias:d}=u[t];if(d?.match(/./))try{if(!f.filter(e=>e.Key_name===d)[0])throw Error("This Index Does not Exist")}catch(t){await r({queryString:`CREATE${l?.match(/fullText/i)?" FULLTEXT":""} INDEX \`${d}\` ON ${a}(${n?.map(e=>e.value).map(e=>`\`${e}\``).join(",")}) COMMENT 'schema_index'`,database:e})}}let p=await r({queryString:`SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${e}' AND TABLE_NAME='${a}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,database:e});if(p)for(let t=0;t<p.length;t++){let{CONSTRAINT_NAME:l}=p[t];l.match(/PRIMARY/)||await r({queryString:`ALTER TABLE ${a} DROP FOREIGN KEY \`${l}\``,database:e})}for(let l=0;l<_.length;l++){let i;let d=_[l],o=_[l-1],u=_[l+1],{fieldName:E,dataType:N,nullValue:f,primaryKey:T,autoIncrement:b,defaultValue:A,defaultValueLiteral:p,foreignKey:y,updatedField:g}=d;if(E?.match(/^id$|^date_/))continue;let R="",h=S&&S[0]?S.filter((e,a)=>{if(e.Field===E)return i=a,!0}):null,{fieldEntryText:D}=n({columnData:d});if(h&&h[0]?.Field){let{Field:e,Type:a,Null:t,Key:r,Default:n,Extra:d}=h[0],c=l<i;(e!==E||c||N?.toUpperCase()!==a.toUpperCase())&&s?R+=`MODIFY COLUMN ${D}${c?o?.fieldName?" AFTER `"+o.fieldName+"`":u?.fieldName?" BEFORE `"+u.fieldName+"`":"":""}`:R+=`MODIFY COLUMN ${D}`}else o&&o.fieldName?R+=`ADD COLUMN ${D} AFTER \`${o.fieldName}\``:u&&u.fieldName?R+=`ADD COLUMN ${D} BEFORE \`${u.fieldName}\``:R+=`ADD COLUMN ${D}`;if(t.push(R+","),!c&&y){let{destinationTableName:t,destinationTableColumnName:l,cascadeDelete:i,cascadeUpdate:n,foreignKeyName:d}=y,s=`ADD CONSTRAINT \`${d}\` FOREIGN KEY (\`${E}\`) REFERENCES \`${t}\`(\`${l}\`)${i?" ON DELETE CASCADE":""}${n?" ON UPDATE CASCADE":""}`,o=`ALTER TABLE \`${a}\` ${s}`,u=await r({database:e,queryString:o});u?.serverStatus||m.push(u)}}let y=t.join(" ").replace(/,$/,"");if(t.length>1)return await r({queryString:y,database:e});return"No Changes Made to Table"}catch(e){return console.log('Error in "updateTable" shell function =>',e.message),"Error in Updating Table"}}},38864:(e,a,t)=>{t(29021);let l=t(16926);e.exports=async function({queryString:e,queryValuesArray:a,database:t,tableSchema:r}){let i;try{i=e&&a&&Array.isArray(a)&&a[0]?await l({query:e,values:a,database:t}):await l({query:e,database:t})}catch(e){console.log("Shell Vardb Error =>",e.message)}return i}},27836:e=>{e.exports={parse:function(e,a){if(e){if("object"==typeof e)return e;if("string"==typeof e)try{return JSON.parse(e,a)}catch(e){return}}},stringify:function(e,a,t){try{return JSON.stringify(e,a,t)}catch(e){return}}}},95610:e=>{e.exports=JSON.parse('[{"fieldName":"id","dataType":"BIGINT","notNullValue":true,"primaryKey":true,"autoIncrement":true},{"fieldName":"uuid","dataType":"UUID","defaultValueLiteral":"UUID()"},{"fieldName":"date_created","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_created_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_created_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP"},{"fieldName":"date_updated","dataType":"VARCHAR(250)","nullValue":true},{"fieldName":"date_updated_code","dataType":"BIGINT","nullValue":true},{"fieldName":"date_updated_timestamp","dataType":"TIMESTAMP","defaultValueLiteral":"CURRENT_TIMESTAMP","onUpdateLiteral":"CURRENT_TIMESTAMP"}]')}}; |