Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add camel case to timestamps method #4803

Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 21 additions & 7 deletions lib/schema/tablebuilder.js
Expand Up @@ -10,7 +10,7 @@ const each = require('lodash/each');
const extend = require('lodash/extend');
const toArray = require('lodash/toArray');
const helpers = require('../util/helpers');
const { isString, isFunction } = require('../util/is');
const { isString, isFunction, isObject } = require('../util/is');

class TableBuilder {
constructor(client, method, tableName, tableNameLike, fn) {
Expand Down Expand Up @@ -50,16 +50,25 @@ class TableBuilder {
}

// The "timestamps" call is really just sets the `created_at` and `updated_at` columns.

timestamps() {
const method = arguments[0] === true ? 'timestamp' : 'datetime';
const createdAt = this[method]('created_at');
const updatedAt = this[method]('updated_at');
if (arguments[1] === true) {
let useTimestamps, defaultToNow, useCamelCase;
if (isObject(arguments[0])) {
OlivierCavadenti marked this conversation as resolved.
Show resolved Hide resolved
({ useTimestamps, defaultToNow, useCamelCase } = arguments[0]);
} else {
useTimestamps = arguments[0];
defaultToNow = arguments[1];
useCamelCase = arguments[2];
}
const method = useTimestamps === true ? 'timestamp' : 'datetime';
const createdAt = this[method](useCamelCase ? 'createdAt' : 'created_at');
const updatedAt = this[method](useCamelCase ? 'updatedAt' : 'updated_at');

if (defaultToNow === true) {
const now = this.client.raw('CURRENT_TIMESTAMP');
createdAt.notNullable().defaultTo(now);
updatedAt.notNullable().defaultTo(now);
}
return;
}

// Set the comment value for a table, they're only allowed to be called
Expand Down Expand Up @@ -290,7 +299,12 @@ const AlterMethods = {
},

dropTimestamps() {
return this.dropColumns(['created_at', 'updated_at']);
// arguments[0] = useCamelCase
return this.dropColumns(
arguments[0] === true
? ['createdAt', 'updatedAt']
: ['created_at', 'updated_at']
);
},

setNullable(column) {
Expand Down
7 changes: 6 additions & 1 deletion test/integration/logger.js
Expand Up @@ -98,7 +98,12 @@ module.exports = function (knex) {
return _.reduce(
val,
function (memo, val, key) {
if (_.includes(['created_at', 'updated_at'], key)) {
if (
_.includes(
['created_at', 'updated_at', 'createdAt', 'updatedAt'],
key
)
) {
memo[key] = TEST_TIMESTAMP;
} else if (_.includes(['dummy_id'], key)) {
memo[key] = TEST_ID;
Expand Down
42 changes: 42 additions & 0 deletions test/integration2/schema/misc.spec.js
Expand Up @@ -671,6 +671,48 @@ describe('Schema (misc)', () => {
]);
}));

it('create table with timestamps options', async () => {
await knex.schema
.createTable('test_table_timestamp', (table) => {
if (isMysql(knex)) table.engine('InnoDB');
table.bigIncrements('id');
table.timestamps({
useTimestamps: false,
defaultToNow: true,
useCamelCase: true,
});
})
.testSql((tester) => {
tester('mysql', [
'create table `test_table_timestamp` (`id` bigint unsigned not null auto_increment primary key, `createdAt` datetime not null default CURRENT_TIMESTAMP, `updatedAt` datetime not null default CURRENT_TIMESTAMP) default character set utf8 engine = InnoDB',
]);
tester(
['pg', 'cockroachdb'],
[
'create table "test_table_timestamp" ("id" bigserial primary key, "createdAt" timestamptz not null default CURRENT_TIMESTAMP, "updatedAt" timestamptz not null default CURRENT_TIMESTAMP)',
]
);
tester('pg-redshift', [
'create table "test_table_timestamp" ("id" bigint identity(1,1) primary key not null, "createdAt" timestamptz not null default CURRENT_TIMESTAMP, "updatedAt" timestamptz not null default CURRENT_TIMESTAMP)',
]);
tester('sqlite3', [
'create table `test_table_timestamp` (`id` integer not null primary key autoincrement, `createdAt` datetime not null default CURRENT_TIMESTAMP, `updatedAt` datetime not null default CURRENT_TIMESTAMP)',
]);
tester('oracledb', [
`create table "test_table_timestamp"
(
"id" number(20, 0) not null primary key,
"created_at" timestamp with local time zone not null default CURRENT_TIMESTAMP,
"updated_at" timestamp with local time zone not null default CURRENT_TIMESTAMP
)`,
]);
tester('mssql', [
'CREATE TABLE [test_table_timestamp] ([id] bigint identity(1,1) not null primary key, [createdAt] datetime2 not null CONSTRAINT [test_table_timestamp_createdat_default] DEFAULT CURRENT_TIMESTAMP, [updatedAt] datetime2 not null CONSTRAINT [test_table_timestamp_updatedat_default] DEFAULT CURRENT_TIMESTAMP)',
]);
});
await knex.schema.dropTableIfExists('test_table_timestamp');
});

it('is possible to set the db engine with the table.engine', () =>
knex.schema
.createTable('test_table_two', (table) => {
Expand Down
17 changes: 17 additions & 0 deletions test/unit/schema-builder/postgres.js
Expand Up @@ -1619,6 +1619,23 @@ describe('PostgreSQL SchemaBuilder', function () {
);
});

it('adding timestamps with options object', () => {
tableSql = client
.schemaBuilder()
.table('users', (table) => {
table.timestamps({
useTimestamps: true,
defaultToNow: true,
useCamelCase: true,
});
})
.toSQL();
equal(1, tableSql.length);
expect(tableSql[0].sql).to.equal(
'alter table "users" add column "createdAt" timestamptz not null default CURRENT_TIMESTAMP, add column "updatedAt" timestamptz not null default CURRENT_TIMESTAMP'
);
});

it('adding binary', function () {
tableSql = client
.schemaBuilder()
Expand Down
10 changes: 7 additions & 3 deletions types/index.d.ts
Expand Up @@ -2023,8 +2023,12 @@ export declare namespace Knex {
/** @deprecated */
timestamp(columnName: string, withoutTz?: boolean, precision?: number): ColumnBuilder;
timestamps(
useTimestampType?: boolean,
makeDefaultNow?: boolean
useTimestamps?: boolean,
defaultToNow?: boolean,
useCamelCase?: boolean
): ColumnBuilder;
timestamps(
options?: Readonly<{useTimestamps?: boolean, defaultToNow?: boolean, useCamelCase?: boolean}>
): void;
geometry(columnName: string): ColumnBuilder;
geography(columnName: string): ColumnBuilder;
Expand Down Expand Up @@ -2072,7 +2076,7 @@ export declare namespace Knex {
dropUnique(columnNames: readonly (string | Raw)[], indexName?: string): TableBuilder;
dropPrimary(constraintName?: string): TableBuilder;
dropIndex(columnNames: string | readonly (string | Raw)[], indexName?: string): TableBuilder;
dropTimestamps(): TableBuilder;
dropTimestamps(useCamelCase?: boolean): TableBuilder;
queryContext(context: any): TableBuilder;
}

Expand Down