objection-paginator
Version:
Paginated queries for Objection.js
53 lines • 1.76 kB
JavaScript
import { ConfigurationError } from "./configuration-error.js";
export class Column {
constructor(columnName, tableName) {
this.columnName = columnName;
this.tableName = tableName;
}
static validate(str) {
if (this._columnPattern.test(str))
return str;
throw new ConfigurationError(`Invalid column identifier '${str}'`);
}
static parse(str) {
const [columnName, tableName] = str.split(".").reverse();
return new this(columnName, tableName);
}
static extractFromSql(sql, omitTableName = false) {
const match = this._sqlPattern.exec(sql);
if (!match)
return null;
const [, columnName, tableName] = match;
if (omitTableName)
return new this(columnName);
return new this(columnName, tableName);
}
static toRaw(str, qry) {
return this.parse(str).toRaw(qry).serialize();
}
clone() {
return new Column(this.columnName, this.tableName);
}
getMappingQuery(qry) {
return qry.clone().clear(/.*/)
.select(this.columnName)
.from(this.tableName || "some_table");
}
getMappingSql(qry) {
return this.getMappingQuery(qry).toKnexQuery().toSQL().sql;
}
toRaw(qry) {
const sql = this.getMappingSql(qry);
const raw = Column.extractFromSql(sql, !this.tableName);
return raw || this.clone();
}
serialize() {
const terms = [this.columnName];
if (this.tableName)
terms.unshift(this.tableName);
return terms.join(".");
}
}
Column._columnPattern = /^(?:[^.]+\.)?[^.]+$/;
Column._sqlPattern = /^select (["`].*?["`]) from (["`].*?["`])$/;
//# sourceMappingURL=column.js.map