prostgles-server 2.0.188 → 2.0.191

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/DboBuilder/insertDataParse.d.ts.map +1 -1
  2. package/dist/DboBuilder/insertDataParse.js +14 -4
  3. package/dist/DboBuilder/insertDataParse.js.map +1 -1
  4. package/dist/DboBuilder.d.ts +5 -3
  5. package/dist/DboBuilder.d.ts.map +1 -1
  6. package/dist/DboBuilder.js +67 -161
  7. package/dist/DboBuilder.js.map +1 -1
  8. package/dist/FileManager.d.ts +20 -72
  9. package/dist/FileManager.d.ts.map +1 -1
  10. package/dist/FileManager.js +232 -164
  11. package/dist/FileManager.js.map +1 -1
  12. package/dist/Prostgles.d.ts +13 -2
  13. package/dist/Prostgles.d.ts.map +1 -1
  14. package/dist/Prostgles.js.map +1 -1
  15. package/dist/TableConfig.d.ts +1 -2
  16. package/dist/TableConfig.d.ts.map +1 -1
  17. package/dist/TableConfig.js.map +1 -1
  18. package/lib/DboBuilder/insertDataParse.d.ts.map +1 -1
  19. package/lib/DboBuilder/insertDataParse.js +14 -4
  20. package/lib/DboBuilder/insertDataParse.ts +14 -4
  21. package/lib/DboBuilder.d.ts +5 -3
  22. package/lib/DboBuilder.d.ts.map +1 -1
  23. package/lib/DboBuilder.js +67 -161
  24. package/lib/DboBuilder.ts +84 -191
  25. package/lib/FileManager.d.ts +19 -71
  26. package/lib/FileManager.d.ts.map +1 -1
  27. package/lib/FileManager.js +232 -164
  28. package/lib/FileManager.ts +272 -191
  29. package/lib/Prostgles.d.ts +13 -2
  30. package/lib/Prostgles.d.ts.map +1 -1
  31. package/lib/Prostgles.ts +2 -2
  32. package/lib/TableConfig.d.ts +1 -2
  33. package/lib/TableConfig.d.ts.map +1 -1
  34. package/lib/TableConfig.ts +2 -4
  35. package/lib/fileType/core.js +1527 -0
  36. package/lib/fileType/supported.js +278 -0
  37. package/package.json +5 -5
  38. package/tests/client/PID.txt +1 -1
  39. package/tests/server/DBoGenerated.d.ts +1 -1
  40. package/tests/server/package-lock.json +9 -9
package/lib/DboBuilder.ts CHANGED
@@ -155,9 +155,11 @@ export type LocalParams = {
155
155
 
156
156
  returnQuery?: boolean;
157
157
 
158
- nestedJoin?: {
158
+ nestedInsert?: {
159
159
  depth: number;
160
- data: AnyObject;
160
+ previousData: AnyObject;
161
+ previousTable: string;
162
+ referencingColumn?: string;
161
163
  }
162
164
  }
163
165
  function replaceNonAlphaNumeric(string: string, replacement = "_"): string {
@@ -711,7 +713,7 @@ export class ViewHandler {
711
713
  };
712
714
  });
713
715
  let expectOne = false;
714
- paths.map(({ source, target, on }, i) => {
716
+ // paths.map(({ source, target, on }, i) => {
715
717
  // if(expectOne && on.length === 1){
716
718
  // const sourceCol = on[0][1];
717
719
  // const targetCol = on[0][0];
@@ -721,7 +723,7 @@ export class ViewHandler {
721
723
  // console.log({ sourceCol, targetCol, sCol, source, tCol, target, on})
722
724
  // expectOne = sCol.is_pkey && tCol.is_pkey
723
725
  // }
724
- })
726
+ // })
725
727
  return {
726
728
  paths,
727
729
  expectOne
@@ -739,31 +741,30 @@ export class ViewHandler {
739
741
 
740
742
  let has_media: "one" | "many" | undefined = undefined;
741
743
 
742
- /**
743
- * Media is directly related to this table (does not come from a deeply joined table)
744
- */
745
- let has_direct_media = false;
746
-
747
744
  const mediaTable = this.dboBuilder.prostgles?.opts?.fileTable?.tableName;
748
745
 
749
746
  if(!this.is_media && mediaTable){
750
- if(this.dboBuilder.prostgles?.opts?.fileTable?.referencedTables?.[this.name]){
751
- has_media = this.dboBuilder.prostgles?.opts?.fileTable?.referencedTables?.[this.name];
752
- has_direct_media = true;
747
+ const joinConf = this.dboBuilder.prostgles?.opts?.fileTable?.referencedTables?.[this.name]
748
+ if(joinConf){
749
+ has_media = typeof joinConf === "string"? joinConf : "one";
753
750
  } else {
754
751
  const jp = this.dboBuilder.joinPaths.find(jp => jp.t1 === this.name && jp.t2 === mediaTable);
755
752
  if(jp && jp.path.length <= 3){
756
- await Promise.all(jp.path.map(async tableName => {
757
- const cols = (await this?.dboBuilder?.dbo?.[tableName]?.getColumns?.())?.filter(c => jp.path.includes(c?.references?.ftable as any));
758
- if(cols && cols.length && has_media !== "many"){
759
- if(cols.find(c => !c.is_pkey)){
760
- has_media = "many"
761
- } else {
762
- has_media = "one"
753
+ if(jp.path.length <= 2){
754
+ has_media = "one"
755
+ } else {
756
+ await Promise.all(jp.path.map(async tableName => {
757
+ const pkeyFcols = this?.dboBuilder?.dbo?.[tableName]?.columns?.filter(c => c.is_pkey).map(c => c.name);
758
+ const cols = this?.dboBuilder?.dbo?.[tableName]?.columns?.filter(c => c?.references && jp.path.includes(c?.references?.ftable));
759
+ if(cols && cols.length && has_media !== "many"){
760
+ if(cols.some(c => !pkeyFcols?.includes(c.name))){
761
+ has_media = "many"
762
+ } else {
763
+ has_media = "one"
764
+ }
763
765
  }
764
- has_direct_media = jp.path.length === 2;
765
- }
766
- }));
766
+ }));
767
+ }
767
768
  }
768
769
  }
769
770
  }
@@ -774,7 +775,6 @@ export class ViewHandler {
774
775
  info: this.dboBuilder.prostgles?.tableConfigurator?.getTableInfo({ tableName: this.name, lang }),
775
776
  is_media: this.is_media, // this.name === this.dboBuilder.prostgles?.opts?.fileTable?.tableName
776
777
  has_media,
777
- has_direct_media,
778
778
  media_table_name: mediaTable,
779
779
  dynamicRules: {
780
780
  update: Boolean(tableRules?.update?.dynamicFields?.length)
@@ -831,7 +831,11 @@ export class ViewHandler {
831
831
  _delete = this.tableOrViewInfo.privileges.delete;// c.privileges.some(p => p.privilege_type === "DELETE");
832
832
 
833
833
  delete (c as any).privileges;
834
- let result = {
834
+
835
+ const prostgles = this.dboBuilder?.prostgles;
836
+ const fileConfig = prostgles.fileManager?.getColInfo({ colName: c.name, tableName: this.name })
837
+
838
+ let result: ValidatedColumnInfo = {
835
839
  ...c,
836
840
  label,
837
841
  tsDataType: postgresToTsType(c.udt_name),
@@ -840,7 +844,8 @@ export class ViewHandler {
840
844
  filter: Boolean(p.select && p.select.filterFields && p.select.filterFields.includes(c.name)),
841
845
  update: update && Boolean(p.update && p.update.fields && p.update.fields.includes(c.name)),
842
846
  delete: _delete && Boolean(p.delete && p.delete.filterFields && p.delete.filterFields.includes(c.name)),
843
- ...(this.dboBuilder?.prostgles?.tableConfigurator?.getColInfo({ table: this.name, col: c.name, lang }) || {})
847
+ ...(prostgles?.tableConfigurator?.getColInfo({ table: this.name, col: c.name, lang }) || {}),
848
+ ...(fileConfig && { file: fileConfig })
844
849
  }
845
850
 
846
851
  if(dynamicUpdateFields){
@@ -1828,10 +1833,10 @@ export class ViewHandler {
1828
1833
  * @param {FieldFilter} fieldParams - { col1: 0, col2: 0 } | { col1: true, col2: true } | "*" | ["key1", "key2"] | []
1829
1834
  * @param {boolean} allow_empty - allow empty select. defaults to true
1830
1835
  */
1831
- static _parseFieldFilter(fieldParams: FieldFilter = "*", allow_empty: boolean = true, all_cols: string[]): string[] {
1836
+ static _parseFieldFilter<AllowedKeys extends string[]>(fieldParams: FieldFilter<Record<AllowedKeys[number], any>> = "*", allow_empty: boolean = true, all_cols: AllowedKeys): AllowedKeys | [""] {
1832
1837
  if(!all_cols) throw "all_cols missing"
1833
1838
  const all_fields = all_cols;// || this.column_names.slice(0);
1834
- let colNames: string[] = [],
1839
+ let colNames: AllowedKeys = [] as any,
1835
1840
  initialParams = JSON.stringify(fieldParams);
1836
1841
 
1837
1842
  if(fieldParams){
@@ -1849,7 +1854,7 @@ export class ViewHandler {
1849
1854
  ["*"]
1850
1855
  */
1851
1856
  if(fieldParams[0] === "*"){
1852
- return all_fields.slice(0);
1857
+ return all_fields.slice(0) as typeof all_fields;
1853
1858
 
1854
1859
  /*
1855
1860
  [""]
@@ -1864,7 +1869,7 @@ export class ViewHandler {
1864
1869
  ["field1", "field2", "field3"]
1865
1870
  */
1866
1871
  } else {
1867
- colNames = fieldParams.slice(0);
1872
+ colNames = fieldParams.slice(0) as AllowedKeys;
1868
1873
  }
1869
1874
 
1870
1875
  /*
@@ -1873,10 +1878,10 @@ export class ViewHandler {
1873
1878
  */
1874
1879
  } else if(isPlainObject(fieldParams)){
1875
1880
 
1876
- if(Object.keys(fieldParams).length){
1877
- let keys = Object.keys(fieldParams as {
1881
+ if(getKeys(fieldParams).length){
1882
+ let keys = getKeys(fieldParams as {
1878
1883
  [key: string]: boolean | 0 | 1;
1879
- });
1884
+ }) as AllowedKeys;
1880
1885
  if(keys[0] === ""){
1881
1886
  if(allow_empty){
1882
1887
  return [""];
@@ -1897,12 +1902,12 @@ export class ViewHandler {
1897
1902
 
1898
1903
 
1899
1904
  if(disallowed && disallowed.length){
1900
- return all_fields.filter(col => !disallowed.includes(col));
1905
+ return all_fields.filter(col => !disallowed.includes(col)) as typeof all_fields;
1901
1906
  } else {
1902
- return [...allowed];
1907
+ return [...allowed] as any;
1903
1908
  }
1904
1909
  } else {
1905
- return all_fields.slice(0);
1910
+ return all_fields.slice(0) as typeof all_fields;
1906
1911
  }
1907
1912
  } else {
1908
1913
  throw " Unrecognised field filter.\nExpecting any of: string | string[] | { [field]: boolean } \n Received -> " + initialParams;
@@ -1910,9 +1915,9 @@ export class ViewHandler {
1910
1915
 
1911
1916
  validate(colNames);
1912
1917
  }
1913
- return colNames;
1918
+ return colNames as any;
1914
1919
 
1915
- function validate(cols: string[]){
1920
+ function validate(cols: AllowedKeys){
1916
1921
  let bad_keys = cols.filter(col => !all_fields.includes(col));
1917
1922
  if(bad_keys && bad_keys.length){
1918
1923
  throw "\nUnrecognised or illegal fields: " + bad_keys.join(", ");
@@ -2692,20 +2697,23 @@ export class DboBuilder {
2692
2697
  // 3 find incorrect fields
2693
2698
  joins.map(({ tables, on }) => {
2694
2699
  const t1 = tables[0],
2695
- t2 = tables[1],
2696
- f1s = Object.keys(on),
2697
- f2s = Object.values(on);
2698
- [[t1, f1s], [t2, f2s]].map(v => {
2699
- var t = <string>v[0],
2700
- f = <string[]>v[1];
2701
-
2702
- let tov = this.tablesOrViews!.find(_t => _t.name === t);
2703
- if(!tov) throw "Table not found: " + t;
2704
- const m1 = f.filter(k => !tov!.columns.map(c => c.name).includes(k))
2705
- if(m1 && m1.length){
2706
- throw `Table ${t}(${tov.columns.map(c => c.name).join()}) has no fields named: ${m1.join()}`;
2707
- }
2708
- });
2700
+ t2 = tables[1];
2701
+ on.map(cond => {
2702
+
2703
+ const f1s = Object.keys(cond),
2704
+ f2s = Object.values(cond);
2705
+ [[t1, f1s], [t2, f2s]].map(v => {
2706
+ var t = <string>v[0],
2707
+ f = <string[]>v[1];
2708
+
2709
+ let tov = this.tablesOrViews!.find(_t => _t.name === t);
2710
+ if(!tov) throw "Table not found: " + t;
2711
+ const m1 = f.filter(k => !tov!.columns.map(c => c.name).includes(k))
2712
+ if(m1 && m1.length){
2713
+ throw `Table ${t}(${tov.columns.map(c => c.name).join()}) has no fields named: ${m1.join()}`;
2714
+ }
2715
+ });
2716
+ })
2709
2717
  });
2710
2718
 
2711
2719
  // 4 find incorrect/missing join types
@@ -2762,33 +2770,11 @@ export class DboBuilder {
2762
2770
 
2763
2771
  async build(): Promise<DBHandlerServer>{
2764
2772
 
2765
- // await this.pubSubManager.init()
2766
-
2767
- this.tablesOrViews = await getTablesForSchemaPostgresSQL(this.db); //, this.schema
2768
- // console.log(this.tablesOrViews.map(t => `${t.name} (${t.columns.map(c => c.name).join(", ")})`))
2773
+ this.tablesOrViews = await getTablesForSchemaPostgresSQL(this.db);
2769
2774
 
2770
2775
  this.constraints = await getConstraints(this.db);
2771
2776
  await this.parseJoins();
2772
2777
 
2773
- // const common_types =
2774
- // `
2775
-
2776
- // import { ViewHandler, TableHandler, JoinMaker } from "prostgles-types";
2777
-
2778
- // export type TxCB = {
2779
- // (t: DBObj): (any | void | Promise<(any | void)>)
2780
- // };
2781
-
2782
- // `
2783
- // this.dboDefinition = `export type DBObj = {\n`;
2784
-
2785
-
2786
- // let joinTableNames: string[] = [];
2787
-
2788
- // let allDataDefs = "";
2789
-
2790
-
2791
-
2792
2778
  this.tablesOrViews.map(tov => {
2793
2779
  const columnsForTypes = tov.columns.slice(0).sort((a, b) => a.name.localeCompare(b.name));
2794
2780
 
@@ -2800,26 +2786,12 @@ export class DboBuilder {
2800
2786
  Please provide a replacement keyword name using the $filter_keyName init option.
2801
2787
  Alternatively you can rename the table column\n`;
2802
2788
  }
2803
-
2804
- const TSTableDataName = snakify(tov.name, true);
2805
- const TSTableHandlerName = escapeTSNames(tov.name)
2806
- if(tov.is_view){
2807
- this.dbo[tov.name] = new ViewHandler(this.db, tov, this, undefined, undefined, this.joinPaths);
2808
- // this.dboDefinition += ` ${TSTableHandlerName}: ViewHandler<${TSTableDataName}> \n`;
2809
- } else {
2810
- this.dbo[tov.name] = new TableHandler(this.db, tov, this, undefined, undefined, this.joinPaths);
2811
- // this.dboDefinition += ` ${TSTableHandlerName}: TableHandler<${TSTableDataName}> \n`;
2812
- }
2813
- // allDataDefs += `export type ${TSTableDataName} = { \n` +
2814
- // (this.dbo[tov.name] as ViewHandler).tsColumnDefs.map(str => ` ` + str).join("\n") +
2815
- // `\n}\n`;
2816
-
2817
- // this.dboDefinition += ` ${escapeTSNames(tov.name, false)}: ${(this.dbo[tov.name] as TableHandler).tsDboName};\n`;
2789
+
2790
+ this.dbo[tov.name] = new (tov.is_view? ViewHandler : TableHandler)(this.db, tov, this, undefined, undefined, this.joinPaths);
2818
2791
 
2819
2792
  if(this.joinPaths && this.joinPaths.find(jp => [jp.t1, jp.t2].includes(tov.name))){
2820
2793
 
2821
2794
  let table = tov.name;
2822
- // joinTableNames.push(table);
2823
2795
 
2824
2796
  const makeJoin = (
2825
2797
  isLeft = true,
@@ -2853,19 +2825,6 @@ export class DboBuilder {
2853
2825
  }
2854
2826
  });
2855
2827
 
2856
- // let joinBuilderDef = "";
2857
- // if(joinTableNames.length){
2858
- // joinBuilderDef += "export type JoinMakerTables = {\n";
2859
- // joinTableNames.map(tname => {
2860
- // joinBuilderDef += ` ${escapeTSNames(tname)}: JoinMaker<${snakify(tname, true)}>;\n`
2861
- // })
2862
- // joinBuilderDef += "};\n";
2863
- // ["leftJoin", "innerJoin", "leftJoinOne", "innerJoinOne"].map(joinType => {
2864
- // this.dboDefinition += ` ${joinType}: JoinMakerTables;\n`;
2865
- // });
2866
- // }
2867
-
2868
-
2869
2828
  if(this.prostgles.opts.transactions){
2870
2829
  let txKey = "tx";
2871
2830
  if(typeof this.prostgles.opts.transactions === "string") txKey = this.prostgles.opts.transactions;
@@ -2876,7 +2835,7 @@ export class DboBuilder {
2876
2835
 
2877
2836
  if(!this.dbo.sql){
2878
2837
 
2879
- let needType = true;// this.publishRawSQL && typeof this.publishRawSQL === "function";
2838
+ let needType = true;
2880
2839
  let DATA_TYPES: {oid: string, typname: PG_COLUMN_UDT_DATA_TYPE }[] = !needType? [] : await this.db.any("SELECT oid, typname FROM pg_type");
2881
2840
  let USER_TABLES: { relid: string; relname: string; }[] = !needType? [] : await this.db.any("SELECT relid, relname FROM pg_catalog.pg_statio_user_tables");
2882
2841
 
@@ -2982,39 +2941,21 @@ export class DboBuilder {
2982
2941
  this.dboDefinition += "};\n";
2983
2942
 
2984
2943
  this.tsTypesDefinition = [
2985
- // common_types,
2986
2944
  `/* SCHEMA DEFINITON. Table names have been altered to work with Typescript */`,
2987
- // allDataDefs,
2988
- // joinBuilderDef,
2989
-
2990
- `/* DBO Definition. Isomorphic */`,
2991
- // this.dboDefinition,
2945
+ `/* DBO Definition */`,
2992
2946
  getDBSchema(this)
2993
2947
  ].join("\n");
2994
2948
 
2995
2949
  return this.dbo;
2996
- // let dbo = makeDBO(db, allTablesViews, pubSubManager, true);
2997
2950
  }
2998
2951
 
2999
2952
  getTX = (cb: TxCB) => {
3000
2953
  return this.db.tx((t) => {
3001
2954
  let dbTX: TableHandlers = {};
3002
2955
  this.tablesOrViews?.map(tov => {
3003
- if(tov.is_view){
3004
-
3005
- dbTX[tov.name] = new ViewHandler(this.db, tov, this, t, dbTX, this.joinPaths);
3006
- } else {
3007
- dbTX[tov.name] = new TableHandler(this.db, tov, this, t, dbTX, this.joinPaths);
3008
-
3009
- /**
3010
- * Pass only the transaction object to ensure consistency
3011
- */
3012
- // dbTX[tov.name] = new ViewHandler(t, tov, this.pubSubManager, this, t, this.joinPaths);
3013
- // } else {
3014
- // dbTX[tov.name] = new TableHandler(t as any, tov, this.pubSubManager, this, t, this.joinPaths);
3015
- }
2956
+ dbTX[tov.name] = new (tov.is_view? ViewHandler: TableHandler)(this.db, tov, this, t, dbTX, this.joinPaths);
3016
2957
  });
3017
- Object.keys(dbTX).map(k => {
2958
+ getKeys(dbTX).map(k => {
3018
2959
  dbTX[k].dbTX = dbTX;
3019
2960
  })
3020
2961
  return cb(dbTX, t);
@@ -3213,16 +3154,6 @@ async function getTablesForSchemaPostgresSQL(db: DB, schema: string = "public"):
3213
3154
  // console.log(pgp.as.format(query, { schema }), schema);
3214
3155
  let res: TableSchema[] = await db.any(query, { schema });
3215
3156
 
3216
- // res = await Promise.all(res.map(async tbl => {
3217
- // tbl.columns = await Promise.all(tbl.columns.map(async col => {
3218
- // if(col.has_default){
3219
- // col.column_default = !col.column_default.startsWith("nextval(")? (await db.oneOrNone(`SELECT ${col.column_default} as val`)).val : null;
3220
- // }
3221
- // return col;
3222
- // }))
3223
-
3224
- // return tbl;
3225
- // }))
3226
3157
  res = res.map(tbl => {
3227
3158
  tbl.columns = tbl.columns.map(col => {
3228
3159
  if(col.has_default){
@@ -3242,10 +3173,8 @@ async function getTablesForSchemaPostgresSQL(db: DB, schema: string = "public"):
3242
3173
 
3243
3174
  /**
3244
3175
  * Throw error if illegal keys found in object
3245
- * @param {Object} obj - Object to be checked
3246
- * @param {string[]} allowedKeys - The name of the employee.
3247
3176
  */
3248
- function validateObj(obj: object, allowedKeys: string[]): object{
3177
+ function validateObj<T extends Record<string, any>>(obj: T, allowedKeys: string[]): T {
3249
3178
  if(obj && Object.keys(obj).length){
3250
3179
  const invalid_keys = Object.keys(obj).filter(k => !allowedKeys.includes(k));
3251
3180
  if(invalid_keys.length){
@@ -3523,15 +3452,20 @@ function sqlErrCodeToMsg(code: string){
3523
3452
  }
3524
3453
 
3525
3454
 
3526
- async function getInferredJoins2(schema: TableSchema[]): Promise<Join[]>{
3455
+ async function getInferredJoins2(schema: TableSchema[]): Promise<Join[]> {
3527
3456
  let joins: Join[] = [];
3528
- const upsertJoin = (t1: string, t2: string, cols: { col1: string; col2: string }[]) => {
3457
+ const upsertJoin = (t1: string, t2: string, cols: { col1: string; col2: string }[], type: Join["type"]) => {
3529
3458
  let existingIdx = joins.findIndex(j => j.tables.slice(0).sort().join() === [t1, t2].sort().join());
3530
3459
  let existing = joins[existingIdx];
3531
3460
  const normalCond = cols.reduce((a, v) => ({ ...a, [v.col1]: v.col2 }), {});
3532
3461
  const revertedCond = cols.reduce((a, v) => ({ ...a, [v.col2]: v.col1 }), {});
3533
3462
  if(existing){
3534
- const cond = existing.tables[0] === t1? normalCond : revertedCond;
3463
+ const isLTR = existing.tables[0] === t1
3464
+ const cond = isLTR? normalCond : revertedCond;
3465
+
3466
+ /** At some point we should add relationship type to EACH JOIN CONDITION GROUP */
3467
+ // const fixedType = isLTR? type : type.split("").reverse().join("") as Join["type"];
3468
+
3535
3469
  /** Avoid duplicates */
3536
3470
  if(!existing.on.some(_cond => JSON.stringify(_cond) === JSON.stringify(cond))){
3537
3471
  existing.on.push(cond);
@@ -3541,7 +3475,7 @@ async function getInferredJoins2(schema: TableSchema[]): Promise<Join[]>{
3541
3475
  joins.push({
3542
3476
  tables: [t1, t2],
3543
3477
  on: [normalCond],
3544
- type: "many-many"
3478
+ type
3545
3479
  })
3546
3480
  }
3547
3481
  }
@@ -3549,56 +3483,15 @@ async function getInferredJoins2(schema: TableSchema[]): Promise<Join[]>{
3549
3483
  tov.columns.map(col => {
3550
3484
  if(col.references){
3551
3485
  const r = col.references;
3552
- upsertJoin(tov.name, r.ftable, r.cols.map((c, i) => ({ col1: c, col2: r.fcols[i] })))
3486
+ const joinCols = r.cols.map((c, i) => ({ col1: c, col2: r.fcols[i] }));
3487
+ let type: Join["type"] = "one-many";
3488
+ const ftablePkeys = schema.find(_tov => _tov.name === r.ftable)?.columns.filter(fcol => fcol.is_pkey);
3489
+ if(ftablePkeys?.length && ftablePkeys.every(fkey => r.fcols.includes(fkey.name))){
3490
+ type = "one-one";
3491
+ }
3492
+ upsertJoin(tov.name, r.ftable, joinCols, type)
3553
3493
  }
3554
3494
  })
3555
3495
  })
3556
3496
  return joins;
3557
- }
3558
- // async function getInferredJoins(db: DB, schema: string = "public"): Promise<Join[]>{
3559
- // let joins: Join[] = [];
3560
- // let res = await db.any(`SELECT
3561
- // tc.table_schema,
3562
- // tc.constraint_name,
3563
- // tc.table_name,
3564
- // kcu.column_name,
3565
- // ccu.table_schema AS foreign_table_schema,
3566
- // ccu.table_name AS foreign_table_name,
3567
- // ccu.column_name AS foreign_column_name,
3568
- // tc.constraint_type IN ('UNIQUE', 'PRIMARY KEY') as foreign_is_unique
3569
- // FROM
3570
- // information_schema.table_constraints AS tc
3571
- // JOIN information_schema.key_column_usage AS kcu
3572
- // ON tc.constraint_name = kcu.constraint_name
3573
- // AND tc.table_schema = kcu.table_schema
3574
- // JOIN information_schema.constraint_column_usage AS ccu
3575
- // ON ccu.constraint_name = tc.constraint_name
3576
- // AND ccu.table_schema = tc.table_schema
3577
- // WHERE tc.table_schema=` + "${schema}" + `
3578
- // AND tc.constraint_type = 'FOREIGN KEY'
3579
- // AND tc.table_name <> ccu.table_name -- Exclude self-referencing tables
3580
- // `, { schema });
3581
-
3582
- // res.map((d: any) => {
3583
- // let eIdx = joins.findIndex(j => j.tables.includes(d.table_name) && j.tables.includes(d.foreign_table_name));
3584
- // let existing = joins[eIdx];
3585
- // if(existing){
3586
- // if(existing.tables[0] === d.table_name){
3587
- // existing.on = { ...existing.on, [d.column_name]: d.foreign_column_name }
3588
- // } else {
3589
- // existing.on = { ...existing.on, [d.foreign_column_name]: d.column_name }
3590
- // }
3591
- // joins[eIdx] = existing;
3592
- // } else {
3593
- // joins.push({
3594
- // tables: [d.table_name, d.foreign_table_name],
3595
- // on: {
3596
- // [d.column_name]: d.foreign_column_name
3597
- // },
3598
- // type: "many-many"
3599
- // })
3600
- // }
3601
- // });
3602
-
3603
- // return joins;
3604
- // }
3497
+ }
@@ -1,6 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import { S3 } from 'aws-sdk';
3
3
  import { DB, DBHandlerServer, Prostgles } from './Prostgles';
4
+ import { ALLOWED_CONTENT_TYPE, ALLOWED_EXTENSION, ValidatedColumnInfo } from 'prostgles-types';
4
5
  export declare const asSQLIdentifier: (name: string, db: DB) => Promise<string>;
5
6
  export declare type ImageOptions = {
6
7
  keepMetadata?: boolean;
@@ -60,10 +61,14 @@ export default class FileManager {
60
61
  tableName?: string;
61
62
  private fileRoute?;
62
63
  constructor(config: FileManager["config"], imageOptions?: ImageOptions);
63
- getMIME(file: Buffer | String, fileName: string, allowedExtensions?: Array<ALLOWED_EXTENSION>, dissallowedExtensions?: Array<ALLOWED_EXTENSION>, onlyFromName?: boolean): Promise<{
64
- mime: string;
65
- ext: string | ALLOWED_EXTENSION;
64
+ parseFile(args: {
65
+ file: Buffer | string;
66
66
  fileName: string;
67
+ colName?: string;
68
+ tableName?: string;
69
+ }): Promise<{
70
+ mime: string | ALLOWED_CONTENT_TYPE;
71
+ ext: string | ALLOWED_EXTENSION;
67
72
  }>;
68
73
  private upload;
69
74
  uploadAsMedia: (params: {
@@ -74,77 +79,20 @@ export default class FileManager {
74
79
  }) => Promise<UploadedItem>;
75
80
  private getFileURL;
76
81
  private parseSQLIdentifier;
82
+ getColInfo: (args: {
83
+ tableName: string;
84
+ colName: string;
85
+ }) => ValidatedColumnInfo["file"] | undefined;
77
86
  init: (prg: Prostgles) => Promise<void>;
78
87
  }
79
- declare const CONTENT_TYPE_TO_EXT: {
80
- readonly "text/html": readonly ["html", "htm", "shtml"];
81
- readonly "text/css": readonly ["css"];
82
- readonly "text/xml": readonly ["xml"];
83
- readonly "text/mathml": readonly ["mml"];
84
- readonly "text/plain": readonly ["txt"];
85
- readonly "text/vnd.sun.j2me.app-descriptor": readonly ["jad"];
86
- readonly "text/vnd.wap.wml": readonly ["wml"];
87
- readonly "text/x-component": readonly ["htc"];
88
- readonly "image/gif": readonly ["gif"];
89
- readonly "image/jpeg": readonly ["jpeg", "jpg"];
90
- readonly "image/png": readonly ["png"];
91
- readonly "image/tiff": readonly ["tif", "tiff"];
92
- readonly "image/vnd.wap.wbmp": readonly ["wbmp"];
93
- readonly "image/x-icon": readonly ["ico"];
94
- readonly "image/x-jng": readonly ["jng"];
95
- readonly "image/x-ms-bmp": readonly ["bmp"];
96
- readonly "image/svg+xml": readonly ["svg"];
97
- readonly "image/webp": readonly ["webp"];
98
- readonly "application/x-javascript": readonly ["js"];
99
- readonly "application/atom+xml": readonly ["atom"];
100
- readonly "application/rss+xml": readonly ["rss"];
101
- readonly "application/java-archive": readonly ["jar", "war", "ear"];
102
- readonly "application/mac-binhex40": readonly ["hqx"];
103
- readonly "application/msword": readonly ["doc", "docx"];
104
- readonly "application/pdf": readonly ["pdf"];
105
- readonly "application/postscript": readonly ["ps", "eps", "ai"];
106
- readonly "application/rtf": readonly ["rtf"];
107
- readonly "application/vnd.ms-excel": readonly ["xls", "xlsx"];
108
- readonly "application/vnd.ms-powerpoint": readonly ["ppt", "pptx"];
109
- readonly "application/vnd.wap.wmlc": readonly ["wmlc"];
110
- readonly "application/vnd.google-earth.kml+xml": readonly ["kml"];
111
- readonly "application/vnd.google-earth.kmz": readonly ["kmz"];
112
- readonly "application/x-7z-compressed": readonly ["7z"];
113
- readonly "application/x-cocoa": readonly ["cco"];
114
- readonly "application/x-java-archive-diff": readonly ["jardiff"];
115
- readonly "application/x-java-jnlp-file": readonly ["jnlp"];
116
- readonly "application/x-makeself": readonly ["run"];
117
- readonly "application/x-perl": readonly ["pl", "pm"];
118
- readonly "application/x-pilot": readonly ["prc", "pdb"];
119
- readonly "application/x-rar-compressed": readonly ["rar"];
120
- readonly "application/x-redhat-package-manager": readonly ["rpm"];
121
- readonly "application/x-sea": readonly ["sea"];
122
- readonly "application/x-shockwave-flash": readonly ["swf"];
123
- readonly "application/x-stuffit": readonly ["sit"];
124
- readonly "application/x-tcl": readonly ["tcl", "tk"];
125
- readonly "application/x-x509-ca-cert": readonly ["der", "pem", "crt"];
126
- readonly "application/x-xpinstall": readonly ["xpi"];
127
- readonly "application/xhtml+xml": readonly ["xhtml"];
128
- readonly "application/zip": readonly ["zip"];
129
- readonly "application/octet-stream": readonly ["bin", "exe", "dll", "deb", "dmg", "eot", "iso", "img", "msi", "msp", "msm"];
130
- readonly "audio/midi": readonly ["mid", "midi", "kar"];
131
- readonly "audio/mpeg": readonly ["mp3"];
132
- readonly "audio/ogg": readonly ["ogg"];
133
- readonly "audio/x-realaudio": readonly ["ra"];
134
- readonly "video/3gpp": readonly ["3gpp", "3gp"];
135
- readonly "video/mpeg": readonly ["mpeg", "mpg"];
136
- readonly "video/quicktime": readonly ["mov"];
137
- readonly "video/x-flv": readonly ["flv"];
138
- readonly "video/x-mng": readonly ["mng"];
139
- readonly "video/x-ms-asf": readonly ["asx", "asf"];
140
- readonly "video/x-ms-wmv": readonly ["wmv"];
141
- readonly "video/x-msvideo": readonly ["avi"];
142
- readonly "video/mp4": readonly ["m4v", "mp4"];
143
- readonly "video/webm": readonly ["webm"];
88
+ export declare const getFileTypeFromFilename: (fileName: string) => {
89
+ mime: ALLOWED_CONTENT_TYPE;
90
+ ext: ALLOWED_EXTENSION;
144
91
  };
145
- export declare type ALLOWED_CONTENT_TYPE = keyof typeof CONTENT_TYPE_TO_EXT;
146
- export declare type ALLOWED_EXTENSION = (typeof CONTENT_TYPE_TO_EXT)[ALLOWED_CONTENT_TYPE][number];
147
- export {};
92
+ export declare const getFileType: (file: Buffer | string, fileName: string) => Promise<{
93
+ mime: ALLOWED_CONTENT_TYPE;
94
+ ext: ALLOWED_EXTENSION;
95
+ }>;
148
96
  /**
149
97
  *
150
98
 
@@ -1 +1 @@
1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