Skip to content

Commit

Permalink
feat: support tables without primary key
Browse files Browse the repository at this point in the history
  • Loading branch information
nicosantangelo committed May 28, 2019
1 parent 5b56340 commit 0d6e9a0
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/Model.ts
Expand Up @@ -189,7 +189,7 @@ export class Model<T> {
)
const newRow = insertion.rows[0]

if (newRow) {
if (newRow && this.primaryKey) {
row[this.primaryKey] = newRow[this.primaryKey]
}

Expand Down
10 changes: 6 additions & 4 deletions src/db/postgres.ts
Expand Up @@ -106,7 +106,7 @@ export class Postgres {
async insert(
tableName: string,
changes: QueryPart,
primaryKey: string = 'id',
primaryKey: string = '',
onConflict: OnConflict = { target: [], changes: {} }
): Promise<any> {
if (!changes) {
Expand All @@ -117,6 +117,7 @@ export class Postgres {

const values = Object.values(changes)
const conflictValues = Object.values(onConflict.changes || {})
const returning = primaryKey ? `RETURNING ${primaryKey}` : ''

return this.client.query(
`INSERT INTO ${tableName}(
Expand All @@ -125,7 +126,7 @@ export class Postgres {
${this.toValuePlaceholders(changes)}
)
${this.toOnConflictUpsert(onConflict, values.length)}
RETURNING ${primaryKey}`,
${returning}`,
values.concat(conflictValues)
)
}
Expand Down Expand Up @@ -212,13 +213,14 @@ export class Postgres {
rows: string[],
options: { sequenceName?: string; primaryKey?: string } = {}
): Promise<void> {
const { sequenceName = `${tableName}_id_seq`, primaryKey = 'id' } = options
const { sequenceName = `${tableName}_id_seq`, primaryKey = '' } = options
const primaryKeyClause = primaryKey ? `PRIMARY KEY ("${primaryKey}")` : ''

if (sequenceName) await this.createSequence(sequenceName)

await this.client.query(`CREATE TABLE IF NOT EXISTS "${tableName}" (
${rows}
PRIMARY KEY ("${primaryKey}")
${primaryKeyClause}
);`)

if (sequenceName) await this.alterSequenceOwnership(sequenceName, tableName)
Expand Down

0 comments on commit 0d6e9a0

Please sign in to comment.