-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
61 lines (54 loc) · 1.74 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const knex = require('knex');
const db = knex({
client: 'sqlite3',
connection: {
filename: './tire-shop.sqlite'
},
useNullAsDefault: true
});
function setupDatabase() {
db.schema.hasTable('customers').then((exists) => {
if (!exists) {
return db.schema.createTable('customers', (table) => {
table.increments('id').primary();
table.string('name');
table.string('contactNumber');
table.string('city');
table.timestamps(true, true); // adds created_at and updated_at columns
});
}
});
db.schema.hasTable('tires').then((exists) => {
if (!exists) {
return db.schema.createTable('tires', (table) => {
table.increments('id').primary();
table.string('brand'); // change 'name' to 'brand' to avoid conflict with UI display
table.string('size');
table.integer('quantity');
table.float('price');
table.timestamps(true, true); // adds created_at and updated_at columns
});
}
});
db.schema.hasTable('sales').then((exists) => {
if (!exists) {
return db.schema.createTable('sales', (table) => {
table.increments('id').primary();
table.integer('customerId').references('id').inTable('customers');
table.integer('tireId').references('id').inTable('tires');
table.integer('quantity');
table.float('totalPrice');
table.timestamp('date').defaultTo(db.fn.now());
});
}
});
}
function getTires() {
return db('tires').select('id', 'brand', 'size', 'quantity', 'price');
}
function updateTireStock(tireId, newQuantity) {
return db('tires')
.where('id', tireId)
.update('quantity', newQuantity);
}
module.exports = { setupDatabase, db, getTires, updateTireStock };