CodeIgniter4 icon indicating copy to clipboard operation
CodeIgniter4 copied to clipboard

Bug: Forge create CREATE INDEX and UNIQUE

Open okatse opened this issue 3 years ago • 2 comments

This add Index $this->forge->addKey('username');

This add Unique Key $this->forge->addUniqueKey('username');

CREATE INDEX "users_username" ON "public"."users" ("username"); ALTER TABLE "public"."users" ADD CONSTRAINT "users_username" UNIQUE ("username");

In both cases, the _processIndexes method generates the same names Perhaps CREATE INDEX is missing a prefix for example: CREATE INDEX "users_username_IDX"

	protected function _processIndexes(string $table)
	{
		$sqls = [];

		for ($i = 0, $c = count($this->keys); $i < $c; $i++)
		{
			$this->keys[$i] = (array) $this->keys[$i];

			for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++)
			{
				if (! isset($this->fields[$this->keys[$i][$i2]]))
				{
					unset($this->keys[$i][$i2]);
				}
			}
			if (count($this->keys[$i]) <= 0)
			{
				continue;
			}

			if (in_array($i, $this->uniqueKeys, true))
			{
				$sqls[] = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table)
						  . ' ADD CONSTRAINT ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i]))
						  . ' UNIQUE (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');';
				continue;
			}

			$sqls[] = 'CREATE INDEX ' . $this->db->escapeIdentifiers($table . '_' . implode('_', $this->keys[$i]))
					  . ' ON ' . $this->db->escapeIdentifiers($table)
					  . ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i])) . ');';
		}

		return $sqls;
	}

okatse avatar Mar 26 '21 08:03 okatse

Related to #5075

najdanovicivan avatar Sep 11 '21 07:09 najdanovicivan

I'm not sure prefix or suffix should be added or not. But longer index name may cause the limit of index name length.

Setting custom index name #5075 seems to be better solution.

kenjis avatar Jan 09 '22 02:01 kenjis