import { isEmpty } from 'lodash';
import { QueryEditorExpressionType, QueryEditorPropertyType } from '../expressions.js';
import '../types.js';

function getRawSqlFn(db) {
  return db.toRawSql ? db.toRawSql : (query) => toRawSql(query, Boolean(db.disableDatasets));
}
function toRawSql({ sql, dataset, catalog, table }, disableDatasets) {
  var _a, _b, _c, _d;
  let rawQuery = "";
  if (!sql || !haveColumns(sql.columns)) {
    return rawQuery;
  }
  rawQuery += createSelectClause(sql.columns);
  if (catalog && dataset && table) {
    rawQuery += `FROM ${catalog}.${dataset}.${table} `;
  } else if (!disableDatasets && dataset && table) {
    rawQuery += `FROM ${dataset}.${table} `;
  } else if (table) {
    rawQuery += `FROM ${table} `;
  }
  if (sql.whereString) {
    rawQuery += `WHERE ${sql.whereString} `;
  }
  if ((_b = (_a = sql.groupBy) == null ? undefined : _a[0]) == null ? undefined : _b.property.name) {
    const groupBy = sql.groupBy.map((g) => g.property.name).filter((g) => !isEmpty(g));
    rawQuery += `GROUP BY ${groupBy.join(", ")} `;
  }
  if ((_c = sql.orderBy) == null ? undefined : _c.property.name) {
    rawQuery += `ORDER BY ${sql.orderBy.property.name} `;
  }
  if (((_d = sql.orderBy) == null ? undefined : _d.property.name) && sql.orderByDirection) {
    rawQuery += `${sql.orderByDirection} `;
  }
  if (sql.limit !== undefined && sql.limit >= 0) {
    rawQuery += `LIMIT ${sql.limit} `;
  }
  return rawQuery;
}
function createSelectClause(sqlColumns) {
  const columns = sqlColumns.map((c) => {
    var _a, _b;
    let rawColumn = "";
    if (c.name) {
      rawColumn += `${c.name}(${(_a = c.parameters) == null ? undefined : _a.map((p) => `${p.name}`)})`;
    } else {
      rawColumn += `${(_b = c.parameters) == null ? undefined : _b.map((p) => `${p.name}`)}`;
    }
    return rawColumn;
  });
  return `SELECT ${columns.join(", ")} `;
}
function haveColumns(columns) {
  if (!columns) {
    return false;
  }
  const haveColumn = columns.some((c) => {
    var _a, _b;
    return ((_a = c.parameters) == null ? undefined : _a.length) || ((_b = c.parameters) == null ? undefined : _b.some((p) => p.name));
  });
  const haveFunction = columns.some((c) => c.name);
  return haveColumn || haveFunction;
}
function setGroupByField(field) {
  return {
    type: QueryEditorExpressionType.GroupBy,
    property: {
      type: QueryEditorPropertyType.String,
      name: field
    }
  };
}
function setPropertyField(field) {
  return {
    type: QueryEditorExpressionType.Property,
    property: {
      type: QueryEditorPropertyType.String,
      name: field
    }
  };
}
function createFunctionField(functionName) {
  return {
    type: QueryEditorExpressionType.Function,
    name: functionName,
    parameters: []
  };
}

export { createFunctionField, getRawSqlFn, haveColumns, setGroupByField, setPropertyField, toRawSql };
//# sourceMappingURL=sql.utils.js.map
