Skip to content

Commit

Permalink
Merge pull request #230 from stillalivx/master
Browse files Browse the repository at this point in the history
Added: Truncate statement
  • Loading branch information
eveningkid committed Apr 17, 2021
2 parents 3045ef7 + 5593537 commit f1be92f
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ export type DatabaseOptions =
export type SyncOptions = {
/** If tables should be dropped if they exist. */
drop?: boolean;
/** If tables should be truncated. Will raise errors if the linked tables don't exist. */
truncate?: boolean;
};

/** Database client which interacts with an external database instance. */
Expand Down Expand Up @@ -187,11 +189,17 @@ export class Database {
*/
async sync(options: SyncOptions = {}) {
if (options.drop) {
for (let i = this._models.length - 1; i >= 0; i--){
for (let i = this._models.length - 1; i >= 0; i--) {
await this._models[i].drop();
}
}

if (options.truncate) {
for (let i = this._models.length - 1; i >= 0; i--) {
await this._models[i].truncate();
}
}

for (const model of this._models) {
await model.createTable();
}
Expand Down
11 changes: 11 additions & 0 deletions lib/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,17 @@ export class Model {
this._isCreatedInDatabase = false;
}

/** Truncate a model in the database. */
static async truncate() {
const truncateQuery = this._options.queryBuilder
.queryForSchema(this)
.table(this.table)
.truncate()
.toDescription();

await this._options.database.query(truncateQuery);
}

/** Create a model in the database. Should not be called from a child model. */
static async createTable() {
if (this._isCreatedInDatabase) {
Expand Down
6 changes: 6 additions & 0 deletions lib/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type OrderDirection = "desc" | "asc";
export type QueryType =
| "create"
| "drop"
| "truncate"
| "select"
| "insert"
| "update"
Expand Down Expand Up @@ -122,6 +123,11 @@ export class QueryBuilder {
return this;
}

truncate() {
this._query.type = "truncate";
return this;
}

select(...fields: (string | FieldAlias)[]) {
this._query.select = fields;
return this;
Expand Down
4 changes: 4 additions & 0 deletions lib/translators/sql-translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ export class SQLTranslator implements Translator {
queryBuilder = queryBuilder.schema[dropTableHelper](query.table);
break;

case "truncate":
queryBuilder = queryBuilder.truncate(query.table);
break;

case "create":
if (!query.fields) {
throw new Error(
Expand Down

0 comments on commit f1be92f

Please sign in to comment.