`createTable` function with dynamic column array

Hey folks, I'm trying to create a create table function; I feel like this should be straight forward and just work. But, I'm obviously missing something. Please let me know if more details are required.

Thank you for your time.  🙏

//....
type ColumnProps = {
  name: string;
  type: 'serial' | 'varchar' | 'integer';
  isUnique?: boolean;
};

type CreateTableProps = {
  tableName: string;
  columns: ColumnProps[];
};

// create table
export const createTable = async ({ tableName, columns }: CreateTableProps) => {
  try {
    const table = db.schema.createTable(tableName);

    columns.forEach((column: ColumnProps) => {
      table.addColumn(column.name, column.type, (col) => {
        if (column.isUnique) {
          return col.notNull().unique();
        }
        return col;
      });
    });
    const res = await table.execute();
    console.log(res);
  } catch (err) {

    console.log(err);
  }
};


It's throwing a generic sqlite error

[Error: SQLITE_ERROR: near ")": syntax error
Emitted 'error' event on Statement instance at:
] {
  errno: 1,
  code: 'SQLITE_ERROR'
}
Was this page helpful?