Skip to content

Commit

Permalink
feat(QueryBuilder): Support .now() default for timestamps
Browse files Browse the repository at this point in the history
  • Loading branch information
RWOverdijk committed Oct 8, 2016
1 parent 27dafef commit d70a8a1
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
42 changes: 41 additions & 1 deletion src/Mapping.ts
Expand Up @@ -95,6 +95,15 @@ export class Mapping<T> {
return this.target;
}

/**
* Raw command for current timestamp.
*
* @returns {Raw}
*/
public now(): Raw {
return new Raw('CURRENT_TIMESTAMP');
}

/**
* Map a field to this property. Examples:
*
Expand Down Expand Up @@ -805,6 +814,37 @@ export class Field {
}
}

/**
* A raw query
*/
export class Raw {
/**
* @type {string}
*/
private query: string;

/**
* @param {string} query
*/
public constructor(query) {
this.setQuery(query);
}

/**
* @returns {string}
*/
getQuery(): string {
return this.query;
}

/**
* @param {string} value
*/
setQuery(value: string) {
this.query = value;
}
}

export interface FieldOptions {
type: string,
primary?: boolean,
Expand All @@ -814,7 +854,7 @@ export interface FieldOptions {
generatedValue?: string,
scale?: number,
nullable?: boolean,
defaultsTo?: any,
defaultTo?: any | Raw,
unsigned?: boolean,
comment?: string,
size?: number,
Expand Down
16 changes: 15 additions & 1 deletion src/SchemaBuilder.ts
@@ -1,4 +1,4 @@
import {Mapping, FieldOptions} from './Mapping';
import {Mapping, FieldOptions, Raw} from './Mapping';
import {EntityInterface, EntityCtor} from './EntityInterface';
import * as Knex from 'knex';
import {Scope} from './Scope';
Expand Down Expand Up @@ -26,6 +26,11 @@ export class SchemaBuilder {
*/
private built: boolean = false;

/**
* @type {Knex}
*/
private client: Knex;

/**
* @type {string[]}
*/
Expand Down Expand Up @@ -53,6 +58,7 @@ export class SchemaBuilder {
*/
public constructor(entityManager: Scope) {
this.entityManager = entityManager;
this.client = entityManager.getStore().getConnection(Store.ROLE_MASTER);
}

/**
Expand Down Expand Up @@ -397,6 +403,14 @@ export class SchemaBuilder {
if (field.primary) {
column.primary();
}

if (field.defaultTo) {
if (field.defaultTo instanceof Raw) {
column.defaultTo(this.client.raw(field.defaultTo.getQuery()));
} else {
column.defaultTo(field.defaultTo);
}
}
}

/**
Expand Down

0 comments on commit d70a8a1

Please sign in to comment.