import { COLUMN_TYPES } from "../constants.ts" ; import type { DatabaseDialect } from "../connect.ts" ; import { quote } from "../utils/dialect.ts" ; /**
 * Represents a table column for Schema
 */ export class ColumnBuilder { private isPrimaryKey : boolean = false ; private isNotNull : boolean = false ; private isUnique : boolean = false ; private isUnsigned : boolean = false ; private defaultValue : any ; private isDefaultValueAnExpression = false ; constructor ( /** The column name */ private name , /** The column type */ private type , /** The column length (varchar only) */ private length ? ) { } /** Make this integer column unsigned */ public unsigned ( ) { this . isUnsigned = true ; return this ; } /** Set this column to be the PRIMARY KEY */ public primary ( ) { this . isPrimaryKey = true ; return this ; } /** Add the NOT NULL constraint */ public notNull ( ) { this . isNotNull = true ; return this ; } /** Add the UNIQUE constraint */ public unique ( ) { this . isUnique = true ; return this ; } param value param isExpression public default ( value , isExpression = false ) { this . defaultValue = value ; this . isDefaultValueAnExpression = isExpression ; return this ; } param dialect public toSQL ( dialect ) { let columnType = COLUMN_TYPES [ this . type ] [ dialect ] . toUpperCase ( ) ; if ( ( this . type === "integer" || this . type === "bigInteger" || this . type === "smallInteger" ) && this . isUnsigned ) { columnType = "UNSIGNED " + columnType ; } if ( this . type === "varchar" ) { columnType += typeof this . length === "number" ? `(${ this . length })` : "(255)" ; } const query = [ `${ quote ( this . name , dialect ) } ${ columnType }` ] ; if ( this . isPrimaryKey ) { query . push ( "PRIMARY KEY" ) ; } if ( this . isNotNull ) { query . push ( "NOT NULL" ) ; } if ( this . isUnique ) { query . push ( "UNIQUE" ) ; } const isIncrement = this . type === "increments" || this . type === "smallIncrements" || this . type === "bigIncrements" ; if ( isIncrement && ( dialect === "mysql" || dialect === "sqlite" ) ) { query . push ( dialect === "mysql" ? "AUTO_INCREMENT" : "AUTOINCREMENT" ) ; } const defaultValue = this . getDefaultValueSQL ( dialect ) ; if ( defaultValue ) { query . push ( defaultValue ) ; } return query . join ( " " ) ; } /**
     * Get the default value text of the column
     */ private getDefaultValueSQL ( dialect ) { if ( this . defaultValue === null ) { return "DEFAULT NULL" ; } else if ( typeof this . defaultValue === "boolean" ) { if ( dialect === "sqlite" || dialect === "mysql" ) { return `DEFAULT ${ this . defaultValue ? 1 : 0 }` ; } else { return `DEFAULT ${ this . defaultValue ? "true" : "false" }` ; } } else if ( typeof this . defaultValue === "number" ) { return `DEFAULT ${ this . defaultValue }` ; } else if ( typeof this . defaultValue === "string" ) { const value = this . isDefaultValueAnExpression ? this . defaultValue : `'${ this . defaultValue }'` ; return `DEFAULT ${ value }` ; } else { return null ; } } }